The use of vue3 watch and watchEffect and what are the differences

  • 2021-10-25 05:39:58
  • OfStack

1. watch listener

Introducing watch


import { ref, reactive, watch, toRefs } from 'vue'

Listening on Basic Data Types--watch Features:

1. lazy will not be executed when the first page is displayed, but will only be executed when the data changes

2. Parameters can get the current value and the original value

3. You can listen to the changes of multiple data, and use one to listen to the load


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

Listening on reference types--


setup() {
	const nameObj = reactive({name: 'leilei', englishName: 'bob'})
  Eavesdropping 1 Data 
	watch(() => nameObj.name, (curVal, prevVal) => {
 	console.log(curVal, prevVal)
 })
  Listen for multiple data  
	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" />`

2.watchEffect

There are no too many arguments, only one callback function

1. Execute immediately. Without inertia, the first load of the page will be executed.

2. Automatically detect internal code, and if there are dependencies in the code, it will be executed

3. No need to pass the content to listen will automatically perceive the code dependency, no need to pass many parameters, just pass a callback function

4. You can't get the value of previous data, only the current value

5.1 Some = asynchronous operations would be more appropriate here


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

Cancel listener watch Cancel listener usage is the same


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)
 })

watch can also become non-lazy and execute 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
 })

The above is the use of vue3 watch and watchEffect and what are the differences. For more information about vue3 watch and watchEffect, please pay attention to other related articles on this site!


Related articles: