Vue3中的watch

今天继续和大家一起探讨在Vue3中的CompositionAPI中,是如何处理watch的,我们先看一段针对基础数据类型数据的编码方式

const app = Vue.createApp({
    setup(){
        const { ref,watch } = Vue
        const name = ref('lilei')
        // 具有惰性
        // 可以拿到当前值和之前的值
        watch(name, (currentVal,preVal) => {
            console.log(currentVal,preVal)
        })
        return {name}
    },
    template: `<div>
        Name:<input v-model="name" />
        </div>
        <div>Name is {{ name }}</div>`,
    
})
const vm = app.mount("#root")

同样,我们也可以针对引用数据类型,就像这样

const app = Vue.createApp({
    setup(){
        const { reactive,watch } = Vue
        const nameObj = reactive({name:'lilei'})
        watch(() => nameObj.name, (currentVal,preVal) => {
            console.log(currentVal,preVal)
        })
        return {nameObj}
    },
    template: `<div>
        Name:<input v-model="nameObj.name" />
        </div>
        <div>Name is {{ nameObj.name }}</div>`,
    
})
const vm = app.mount("#root")

当然,watch不仅仅可以监控单一的数据,也可以监控多个数据的变化,就像这样

const app = Vue.createApp({
    setup(){
        const { reactive,watch,toRefs } = Vue
        const nameObj = reactive({name:'lilei',englishname:'hanmeimei'})
        
        watch(() => nameObj.name, (currentVal,preVal) => {
            console.log(currentVal,preVal)
        })

        watch(() => nameObj.englishname, (currentVal,preVal) => {
            console.log(currentVal,preVal)
        })

        const {name,englishname} = toRefs(nameObj)
        return {name,englishname} 
    },
    template: `<div>
        Name:<input v-model="name" />
        </div>
        <div>Name is {{ name }}</div>
        <div>
        EnglishName:<input v-model="englishname" />
        </div>
        <div>EnglishName is {{ englishname }}</div>`,
    
})
const vm = app.mount("#root")

同样,我们的代码有一些啰嗦,当然,我们也可以简写成这样

const app = Vue.createApp({
    setup(){
        const { reactive,watch,toRefs } = Vue
        const nameObj = reactive({name:'lilei',englishname:'hanmeimei'})
        // 要注意回掉函数的参数顺序和代表意思
        watch([() => nameObj.name,() => nameObj.englishname], ([curName,curNameEng],[preName,preNameEng]) => {
            console.log(curName,preName)
            console.log(curNameEng,preNameEng)
        })

        const {name,englishname} = toRefs(nameObj)
        return {name,englishname} 
    },
    template: `<div>
        Name:<input v-model="name" />
        </div>
        <div>Name is {{ name }}</div>
        <div>
        EnglishName:<input v-model="englishname" />
        </div>
        <div>EnglishName is {{ englishname }}</div>`,
    
})
const vm = app.mount("#root")

大家还可以扫描二维码,关注我的微信公众号,蜗牛全栈。

 

posted @ 2021-11-15 21:44  技术小王  阅读(222)  评论(0编辑  收藏  举报