1. Use of watch
watch(WatcherSource, Callback, [WatchOptions]) type WatcherSource<T> = Ref<T> | (() => T) interface WatchOptions extends WatchEffectOptions { -- deep?: boolean ``// Default: false` -- immediate?: boolean ``// Default: false`}
Parameter description:
- WatcherSource: Used to specify the responsive variable to listen on. WatcherSource can pass in ref responsive data, and reactive responsive objects should be written in the form of functions.
- Callback: The executed callback function can receive the current value newValue in turn, and the previous value oldValue is used as the entry parameter.
- WatchOptions: Support deep and immediate. When deep listening to responsive objects is required, set deep: true; watch is lazy by default. When we set immediate: true, watch will execute the callback function immediately upon initialization.
- In addition, vue3's watch also supports listening for multiple responsive data, and can also manually stop watch listening.
1. Introduce watch
import { watch } from 'vue'
Then inject the listening event in the setup
setup(props){ const state = reactive({ count: 0 , message:'Hellow world' }); watch(state,()=>{ (); --Single monitor }) return { state, } },
2. Listening from multiple data sources
<template> <div> age: {{}} name: {{}} list: <ul> <li v-for="(item, index) in " :key="index"> {{item}} </li> </ul> <hr> <button @click="changeName">Changename</button> <button @click="changeList">Changelist</button> <button @click="changeAge">Changeage</button> </div> </template> <script lang="ts"> import {defineComponent, reactive, watch} from 'vue'; export default defineComponent({ setup () { let obj = reactive({ name: '1111', list: ['222', '222222', '222222'] }) let obj1 = reactive({ age: 18 }) function changeName () { += '+' } function changeList () { [0] += '+' } function changeAge () { ++ } watch([obj, obj1], () => { () if(>28){ watchFunc() // Stop monitoring` } }, { // The page loading will be executed first immediate: true }) return { obj, changeName, changeList, changeAge, obj1 } } }) </script> <style scoped> </style>
Results: When changing the name and age, watch listens to the changes in the data. When the age is greater than 28, we stop listening and change the age again. Due to the stop of the watch, the callback function of the watch is invalid.
Solution: We can listen for changes in multiple values through watch, or we can use naming the watch function, and then stop listening by executing the name() function.
3. Listen to array changes
<template> <div class="watch-test"> <div>refDefine an array:{{arrayRef}}</div> <div>reactiveDefine an array:{{arrayReactive}}</div> </div> <div> <button @click="changeArrayRef">ChangerefDefine an array第一项</button> <button @click="changeArrayReactive">ChangereactiveDefine an array第一项</button> </div> </template> <script> import {ref, reactive, watch} from 'vue' export default { name: 'WatchTest', setup() { const arrayRef = ref([1, 2, 3, 4]) const arrayReactive = reactive([1, 2, 3, 4]) //ref not deep const arrayRefWatch = watch(arrayRef, (newValue, oldValue) => { ('newArrayRefWatch', newValue, 'oldArrayRefWatch', oldValue) }) //ref deep const arrayRefDeepWatch = watch(arrayRef, (newValue, oldValue) => { ('newArrayRefDeepWatch', newValue, 'oldArrayRefDeepWatch', oldValue) }, {deep: true}) //reactive, source is not function const arrayReactiveWatch = watch(arrayReactive, (newValue, oldValue) => { ('newArrayReactiveWatch', newValue, 'oldArrayReactiveWatch', oldValue) }) // Best practices for array monitoring - reactive and the source uses functional return, returning the copied data const arrayReactiveFuncWatch = watch(() => [...arrayReactive], (newValue, oldValue) => { ('newArrayReactiveFuncWatch', newValue, 'oldArrayReactiveFuncWatch', oldValue) }) const changeArrayRef = () => { [0] = 6 } const changeArrayReactive = () => { arrayReactive[0] = 6 } return { arrayRef, arrayReactive, changeArrayRef, changeArrayReactive } } } </script>
Result: When the array is defined as responsive data ref, if deep:true is not added, watch cannot listen to the change of the value; if deep:true is added, watch can detect the change of the data, but the old value is the same as the new value, that is, the old value cannot be obtained. When an array is defined as a responsive object, no processing is done. Watch can detect changes in data, but the old value is the same as the new value; if the watch's data source is written as a function and a copy of the array is cloned through the extension operator, the new value and the old value can be obtained while listening.
Conclusion: When defining an array, it is best to define the data as a reactive object. In this way, when watching, you only need to write the data source into the form of a function and clone an array through the extension operator to return, and you can obtain the new and old values while listening.
4. Listen to the object
<template> <div class="watch-test"> <div>user:{</div> <div>name:{{}}</div> <div>age:{{}}</div> <div>}</div> <div>brand:{{}}</div> <div> <button @click="changeAge">Change age</button> </div> </div> </template> <script> import {ref, reactive, watch} from 'vue' import _ from 'lodash'; export default { name: 'WatchTest', setup() { const objReactive = reactive({user: {name: 'Komatsu Nana', age: '20'}, brand: 'Channel'}) //reactive source is a function const objReactiveWatch = watch(() => objReactive, (newValue, oldValue) => { ('objReactiveWatch') ('new:',(newValue)) ('old:',(oldValue)) }) //reactive, the source is a function, deep: true const objReactiveDeepWatch = watch(() => objReactive, (newValue, oldValue) => { ('objReactiveDeepWatch') ('new:',(newValue)) ('old:',(oldValue)) }, {deep: true}) // Best practice for deep monitoring of objects - reactive and the source uses functional return, returning the deep copy data const objReactiveCloneDeepWatch = watch(() => _.cloneDeep(objReactive), (newValue, oldValue) => { ('objReactiveCloneDeepWatch') ('new:',(newValue)) ('old:',(oldValue)) }) const changeAge = () => { = 26 } return { objReactive, changeAge } } } </script>
Result: When the object is defined as a reactive object, it is returned in the form of a function. If deep:true is not added, the watch cannot listen for the change of the value; and if deep:true is added, the watch can detect the change of the data, but the old value is the same as the new value, that is, the old value cannot be obtained; if the watch data source is written as a function and cloned through deep copy (the deep copy of the lodash library is used here), the new value and the old value can be obtained while listening.
Conclusion: When defining an object, it is best to define the data as a reactive object. In this way, when watching it, you only need to write the data source into the form of a function and clone a copy of the object to return through a deep copy, and you can obtain the new and old values while listening.
5. Conclusion
- 1. Usually we define the original type of data (number, string, etc.) as ref response data, and the reference type of data (array, object) as reactive reactive data;
- 2. When we use watch to listen for data changes and need to obtain new and old values at the same time, we need to define the data source as a function and deeply copy the data source to return. When we only need new values, we can add the deep:true option.
- In fact, it doesn't matter if the data of the reference type is defined as the ref form. You only need to define the data source as the form of a function and copy the data source deeply to obtain the new and old values~ hahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahaha
This is the end of this article about the detailed explanation of the use of Watch monitoring events in Vue3. For more related contents of Vue3 Watch monitoring events, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!