Listening property Watch

Detect data changes in Vue instances and act accordingly (i.e. define your own functions to do something!).

<body>
    <div id="app">Km:<input type="text" v-model="kilometers">M:<input type="text" v-model="meters">
    </div>
    <script src=".. /node_modules/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el: "#app".data: {
                kilometers: 0.meters: 0
            },
            // Define listener listener attributes: meters, kilometers
            // When one of the values changes, the other one is called
            watch: {
                kilometers(val) {
                    this.meters = val * 1000;
                },
                meters(val) {
                    this.kilometers = val / 1000; }}})</script>
</body>
Copy the code

Pay attention to the point

Attention to this point don’t use the arrow function to define the listener attribute, the arrow function the context of the binding is the parent scope, in the example above this point to the window, can lead to this. Meters = undefined, enclosing kilometers = is undefined

Suitable for the scene

Listeners are best used when asynchronous or expensive operations need to be performed when data changes are required. For example, you can start a Web worker to do other things: start a worker to calculate, watch-fib.html to focus on data display

  1. faibnaci.js
// Complete the Fibonacci rating calculation
function fib(n) {
    if (n == 1 || n == 2) return n;
    return arguments.callee(n - 1) + arguments.callee(n - 2);
}
onmessage = function(event) {
    // Convert data to a decimal integer
    var num = parseInt(event.data, 10);
    console.log(num);
    postMessage(fib(num));
}
Copy the code
  1. watch-fib.html
<body>
    <div id="app">
        <input type="text" v-model="num">
        <p v-show="result">{{result}}</p>
    </div>
    <script src=".. /node_modules/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el: "#app".data: {
                num: 0.result: ' '
            },
            methods: {},watch: {
                num(val) {
                    // You can set an intermediate state to indicate that there is no card owner on the page
                    this.result = "Please wait........";
                    if (val > 0) {
                        let worker = new Worker('./fibonaci.js');
                        // Note that this points to
                        worker.onmessage = (event) = > this.result = event.data;
                        worker.postMessage(val);
                    } else {
                        this.result = ' '; }}}})</script>
Copy the code

Listener form

  • Listener method name
  • Listen for property changes on an object
const app = new Vue({
            el: "#app".data: {
                person: {
                    age: 0.name: "Bob"}},watch: {
                person: {
                    handler(val, oldVal) {
                        if (val.age >= 10) {
                            this.info = "Come of age";
                        } else {
                            this.info = "Minor"; }},deep: true}}});Copy the code
  • Deep listening
  • Immediate The listener function executes immediately

Difference from computed attributes

Monitor property is used to monitor the Vue instance data changes, and to respond on the basis of the data changes, such as another data updates, or make asynchronous requests from the server request data, and computational properties difference is that the listener does not need to return the new data, can not be used as a data attribute, when data changes are required to perform asynchronous or overhead operation, Using a listener is most appropriate.

Making the address

https://github.com/suckitfa/watcher-attrs.git
Copy the code

reference

  • Vue.js from Entry to Actual Combat