In Vue, watch itself cannot listen for multiple variables. But we can achieve "listening multiple variables" at once by returning an object with computed attributes and then listening to that object.
- Define the required properties in data
- Returns a computed property containing the individual objects to be listened to
- Listen to this calculated property in watch
For example:
export default { data() { return { msg1: "message1", msg2: "message2" } }, computed: { msgObj() { const { msg1, msg2 } = this return { msg1, msg2 } } }, watch: { msgObj: { handler(newVal, oldVal) { //The values of newVal and oldVal are the values of new and old msgObj, that is, the values of msg1 and msg2 //Next write the operation to be performed here if (newVal.msg1 != oldVal.msg1) { ( "msg1 is change!!!" ) } if (newVal.msg2 != oldVal.msg2) { ( "msg2 is change!!!" ) } }, deep: true } } }
In this way, we realize that we can listen to the changes of two values at once in the watch.
This is also possible if you want to listen for more values at once.
The above is a detailed explanation of the example of using watch to monitor multiple values at once. For more information about Vue watch listening for multiple values at once, please pay attention to my other related articles!