vue3.0 的改变(2) - 06

124 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

上一节介绍了 vue3新增的一些composition API setup ref reactive,这一节继续来看下vue3和vue2中的 computed watch watchEffect 生命周期 区别

1. computed

computed的功能和vue2中是一样的,计算属性,但是在vue3中,他也被放到了setup() 中,我们来看下他的使用

setup(){
    let fullName = computed(()=>{
        return person.firstName + '-' + person.lastName
    })
    //计算属性——完整
    let fullName = computed({
        get(){
            return person.firstName + '-' + person.lastName
        },
        set(value){
            const nameArr = value.split('-')
            person.firstName = nameArr[0]
            person.lastName = nameArr[1]
        }
    })
}
     

2. watch

watch的功能也和vue2中是一样的,但是在vue3中他有两个需要注意的地方

  • 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)。

  • 监视reactive定义的响应式数据中某个属性时:deep配置有效。

    • 情况一:监视ref定义的响应式数据
        watch(sum,(newValue,oldValue)=>{
            console.log('sum变化了',newValue,oldValue)
        },{immediate:true})
    
    • 情况二:监视多个ref定义的响应式数据
        watch([sum,msg],(newValue,oldValue)=>{
                console.log('sum或msg变化了',newValue,oldValue)
        }) 
    
    • 情况三:监视reactive定义的响应式数据
      • 若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue
      • 若watch监视的是reactive定义的响应式数据,则强制开启了深度监视
        // 此处的deep配置不再奏效
        watch(person,(newValue,oldValue)=>{
                console.log('person变化了',newValue,oldValue)
        },{immediate:true,deep:false})
    
    • 情况四:监视reactive定义的响应式数据中的某个属性
        watch(()=>person.job,(newValue,oldValue)=>{
                console.log('person的job变化了',newValue,oldValue)
        },{immediate:true,deep:true}) 
    
    • 情况五:监视reactive定义的响应式数据中的某些属性
        watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
            console.log('person的job变化了',newValue,oldValue)
        },{immediate:true,deep:true})
    
    • 特殊情况
        // 此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效
         watch(()=>person.job,(newValue,oldValue)=>{
            console.log('person的job变化了',newValue,oldValue)
         },{deep:true})
    

3. watchEffect

  • watch:既要指明监视的属性,也要指明监视的回调。
  • watchEffect:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性。
  • watchEffect有点像computed:
    • 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值。
    • 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值。
// watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
watchEffect(()=>{
    const x1 = sum.value
    const x2 = person.age
    console.log('watchEffect配置的回调执行了')
})

4. 生命周期

Vue3.0 中对生命周期做了点改变,Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:

  • beforeDestroy改名为 beforeUnmount
  • destroyed改名为 unmounted

Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:

  • beforeCreate===>setup()
  • created=======>setup()
  • beforeMount ===>onBeforeMount
  • mounted=======>onMounted
  • beforeUpdate===>onBeforeUpdate
  • updated =======>onUpdated
  • beforeUnmount ==>onBeforeUnmount
  • unmounted =====>onUnmounted

image.png