This is the 21st day of my participation in the August More Text Challenge

What is a Watch

Watch is one of the most powerful features of vue.js.

When the value of a concerned variable changes, Watch listens and executes, registering functions that listen to the variable (such as performing some data and message updates based on the change).

Let’s go straight to the code:

<! DOCTYPE HTML > < HTML lang="en"> <head> <title>vue3 vuuE-0n </title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <script SRC ="/vue3.1.5_vue.global.js"></script> </head> <body> <div id="wzApp"> <h3><a V - bind: href = "url" > click access - > child sauce @ CSDN blog < / a > < / h3 > < input v - model = "num1" / > < br / > < input v - model = "num2" / > < br / > < div > {{num1 + num2}}</div> </div> </body> <script> const { createApp,ref,watch } = Vue const url = 'https://blog.csdn.net/qq_28008615'  const num1 = ref("Hello") const num2 = ref("Vue3") const app = { setup() { watch(num1, (newVal, oldVal)=>{ console.log('change from ' + oldVal + ' to ' + newVal) }) return { url, num1, num2 } } } createApp(app).mount('#wzApp') </script> </html>Copy the code

Emphasizes the

Listen for multiple arguments to execute different methods

But these are just some simple examples. In Vue3, Watch can listen to multiple sources and perform different functions.

In VUe3, the same scenario can also be realized through multiple Watches, but in VUe2, only one watch can exist.

Like adding one more listener


            watch(num2, (newVal, oldVal)=>{ 

                console.log('change from ' + oldVal + ' to ' + newVal)

            })
Copy the code

Other readers can try writing some Watch listeners, but VUe3 is still improved.

conclusion

Watch can monitor and track changes in the values of different variables to trigger other actions.

For example, when doing game website equipment sales, you can change according to some state of the page. Change the skin, prompt all kinds of messages. It’s friendlier.

Of course, it can also prompt the activity information according to a fixed time (this can be modified with timer variables, watch cascade update).

So THAT’s it

I am meatball, learn a little knowledge every day. A front-end development hope to encourage more support, thank you