1. Watch the listener

The introduction of watch

import { ref, reactive, watch, toRefs } from 'vue'
Copy the code

Monitoring basic data types —– Watch features: 1. Lazy is not executed when the page is displayed for the first time. 2 is executed only when data changes. Parameter can get the current value and the original value 3. Can listen for multiple data changes, use a listener to load

setup() {
	const name = ref('leilei')
	watch(name, (curVal, prevVal) => {
    	console.log(curVal, prevVal)
    })
}
template: `Name: <input v-model="name" />`
Copy the code

Listen for reference types —–

setup() { const nameObj = reactive({name: 'leilei', englishName: Watch (() => nameobj.name, (curVal, prevVal) => {console.log(curVal, prevVal) => {console.log(curVal, PrevVal)} watch([() => nameobj.name, () => nameobj.name], ([curName, curEng], [prevName, curEng]) => { console.log(curName, curEng, '----', prevName, curEng) setTimeout(() => { stop1() }, 5000) }) const { name, englishName } = toRefs(nameObj) } template: `Name: <input v-model="name" /> englishName: <input v-model="englishName" />`Copy the code

2.watchEffect

1. Execute immediately, no inertia, the first load of the page will execute. 2. Automatic detection of internal code, there is a dependency in the code will be executed 3. There is no need to pass to listen to the content will automatically sense the code dependency, do not need to pass many parameters, just pass a callback function 4. 5. Some = asynchronous operations would be more appropriate here

watchEffect(() => {
	console.log(nameObj.name) 
})
Copy the code

Watch Cancels listeners in the same way

const stop = watchEffect(() => {
	console.log(nameObj.name) 
    setTimeout(() => {
    	stop()
    }, 5000)
})

const stop1 = watch([() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => {
    	console.log(curName, curEng, '----', prevName, curEng)
        setTimeout(() => {
            stop1()
        }, 5000)
    })
Copy the code

Watch can also be made non-lazy and executed immediately by adding the third parameter, immediate: true

 watch([() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => {
    	console.log(curName, curEng, '----', prevName, curEng)
        setTimeout(() => {
            stop1()
        }, 5000)
    }, {
    	immediate: true
    })
Copy the code