Vue3 新特性学习(二)Vue3生命周期VS Vue2.x 及 setup()函数

2,691 阅读2分钟

本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。

对于 Vue3, 已经发布有一段时间了, 也断断续续探索过, 学习过, 但不是太系统, 也没有总结, 借这个周末作个简单的总结:

上文我们对于 Vue3进行了初步的认识, 搭建开发环境, 创建项目, 以及一些新特性的初步体验. 本文继续来学习 Vue3.x

Vue3 仓库 & 文档地址

Vue3 的源码仓库: github.com/vuejs/vue-n…

Vue3 的文档地址: v3.vuejs.org/

一个使用 Vue3 + TypeScript的小实战项目: github.com/xn213/zhihu…

Vue3.x 的生命周期与 Vue2.x 对比

Vue3 生命周期 - 文档: 生命周期

setup 中使用的 hook名称和原来Vue2.x生命周期的对应关系

  • beforeCreate -> 不再需要
  • created -> 不再需要
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeUnmount -> onBeforeUnmount
  • unmounted -> onUnmounted
  • errorCaptured -> onErrorCaptured
  • renderTracked -> onRenderTracked

在代码中演示:

生命周期也同样写在 setup(){} 函数中:

These functions accept a callback that will be executed when the hook is called by the component: 这些声明周期函数接受一个回调函数, 将在组件调用这些勾子函数时去执行.

setup() {
  // mounted()
  onMounted(() => {
    console.log('Component is mounted!')
  })
  onUpdated(() => {
    console.log('updated')
  })
  onRenderTriggered((event) => {
    console.log(event)
  })
}

setup(){} 函数

Vue3.x 中写代码, 不用像 Vue2.x 那样, 要写各种各样的 方法函数中: 比如 methods computed, 各个生命周期内再写一堆各式各样的方法, created() / mounted 的等等

setup 选项是一个接收 props 和 context 参数的函数 此外,我们将 setup 返回的所有内容都暴露给组件的其余部分 (计算属性、方法、生命周期钩子等等) 以及组件的模板。

在 setup 中你应该避免使用 this,因为它不会找到组件实例。setup 的调用发生在 data property、computed property 或 methods 被解析之前,所以它们无法在 setup 中被获取。

在组件中的 setup(){} 函数中书写各种方法:

// src/components/UserRepositories.vue

export default {
  components: { RepositoriesFilters, RepositoriesSortBy, RepositoriesList },
  props: {
    user: {
      type: String,
      required: true
    }
  },
  setup(props) {
    console.log(props) // { user: '' }

    const onFileUploaded = (rawData: ResponseType<ImageProps>) => {
      createMessage(`上传图片Id ${rawData.data._id}`, 'success')
    }

    const onFileUploadedError = (rawData: ResponseType<ImageProps>) => {
      createMessage(`上传图片 Id ${rawData.data._id}`, 'error')
    }

    const columnList = computed(() => {
      return props.list.map(column => {
        if (!column.avatar) {
          column.avatar = {
            url: require('@/assets/column.jpg')
          }
        } else {
          column.avatar.url = column.avatar.url + '?x-oss-process=image/resize,m_pad,h_50,w_50'
        }
        return column
      })
    })
    return {
       // 这里返回的任何内容都可以用于组件的其余部分
       columnList, // 可以返回组件用到的数据
       onFileUploaded, // 可以返回组件用到的方法
       handleFileChange, // 可以返回组件用到的方法 等等
       ...
    }
  }
  // 组件的“其余部分”
}

小结

  1. 参考Vue3 官方文档: Vue3 - setup-组件选项

  2. 本文主要简单学习对比 Vue3.x 和 Vue2.x 的生命周期对比 及 composition API - setup() 函数及其作用等等. 后续继续跟进学习 Vue3.x