vue中watch、computed的使用

297 阅读1分钟

vue3.x中

<script setup>
    import { watch, reactive, computed, ref } from 'vue'
    const state = reactive({ count: 1 })
    // 声明方法 
    const changeCount = () => { state.count = state.count * 2 }
    
    watch( 
        () => router.currentRoute.value.path,    // 监听路由变化
        (newVal, oldVal) => {
            console.log(state.count)
            console.log(`watch监听变化前的数据:${oldVal}`)
            console.log(`watch监听变化后的数据:${newVal}`) 
            store.commit('menu/updataRoute', {
                path: router.currentRoute.value.path,
                title: router.currentRoute.value.meta.title,
                fullPath:  router.currentRoute.value.fullPath
            })
        }, 
        {
            immediate: true, // 立即执行
            deep: true // 深度监听 
        } 
    ) 
   //    同时监听两个
    watch([() => value1, () => value2],([newValue1,newValue2],[oldValue1,oldValue2])=>{
        console.log(newValue1, newValue2)
    },{});
    
     // 监听路由变化
    onBeforeRouteUpdate((to) => {
        // console.log(to);
    })

    
    const count = ref(1) // 通过computed获得doubleCount
    const doubleCount = computed(() => { return count.value * 2 }) // 获取 
    const doubleCount = computed(() => count.value * 2 ) // 获取 
    // 传参, vue3.x中的过滤器已经废除,可用computed过滤
    const doubleCount = computed(() => (value1: number, value2 = 'xxx') => {
        return value1 + 'xxx' + value2
    }) 

</script>


vue2.x中

a: '1'b: {
     c: '2'
},
watch:{
        a(val, oldVal){//普通的watch监听
            console.log("a: "+val, oldVal);
        },
        b:{//深度监听,可监听到对象、数组的变化
            handler(val, oldVal){
                console.log("b.c: "+val.c, oldVal.c);//但是这两个值打印出来却都是一样的
            },
            deep:true
        }
    }

a是一个普通的值,当a的值变化时会被监听到,b是一个对象,不能直接像a那么写,需要深度监听才能捕捉到,但是当我想去捕捉b对象中某一个值的变化时却发现,这样就只能知道对象发生变化却不知道具体哪个值发生了变化;尤其是对象里面结构嵌套过深的时候。而且有时候我们就想关心这个对象中的某个属性,比如c,这个时候可以这样

watch: {
     'a.c': {
         handler: function() {
            //do something
         },
     }
}

或者还可以这样巧用计算属性

computed: {
    getName: function() {
    	return a.c
    }
}
watch: {
     getName: {
         handler: function() {
            //do something
         },
     }
}

将计算属性的返回值改为函数,再进行传值操作。(计算属性传入参数)

computed: {
      // 控制显示的内容
      computedTxt() {
        return function(value) {
          return this.methodGetByteLen(value, 20)
        }
      }
}