组件生命周期函数

万物皆有生命周期。人的生命周期,分别有婴儿期,成熟期、晚年期,在不同的生命时期里所做的工作是不一样的,组件也有生命周期,如下:

  1. <script>
  2. import {
  3. createComponent,
  4. onMounted,
  5. onUpdated,
  6. onUnmounted
  7. } from '@vue/composition-api' //导入相应的生命周期函数
  8. export default createComponent({
  9. setup() {
  10. onMounted(() => {
  11. console.log('mounted!')
  12. })
  13. onUpdated(() => {
  14. console.log('updated!')
  15. })
  16. onUnmounted(() => {
  17. console.log('unmounted!')
  18. })
  19. }
  20. })
  21. </script>

下面是 2.x Options 和 Composition API 的生命周期对照表:

  • beforeCreate -> use setup()
  • created -> use setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured