Conflict of arrow functions in Vue

After learning H5, C3, JS, I can’t wait to start learning Vue framework. Some time ago, I planned to write a common counter case, but I met a small mistake. Record here, I hope you will not encounter.

In the case of writing counters, a flash of inspiration is going to use the arrow function in ES6, just learned to use to practice

< div id = "app" > < button @ click = 'add' > + < / button > < button @ click = 'sub' v - show = "num > 0" > - < / button > < br > the current Numbers: {{num}} < / div > <script> let app = new Vue({ el: '#app', data: { num: 1 }, methods: { add: () => { this.num++; }, sub: () => { this.num--; } } }) </script>Copy the code
So num doesn’t change at any point, right

At first, I thought it was because I was not proficient in using Vue at the beginning. The variables in data were not well defined, so I re-checked and redefined, but it did not work. Then, in the console output test, I found that this.num was undefined

       add: () => {
                console.log(this.num);
                this.num++;
        },
Copy the code

This does not point to the Vue instance, but somewhere else

Looking at the W3C documentation, we found:

Arrow functions do not have their own this. They are not suitable for defining object methods. The this object inside the arrow function is the object at which it is defined, not used. So the arrow function’s this is fixed and cannot be changed or rebound

The official Vue documentation warns users not to use arrow functions:

Finally, we use the normal function constructor method…

        add: function () {
                this.num++;           
        },
        sub: function () {
            this.num--;
        }

Copy the code

Everything is all right

It took a lot of time (a shame…) But found their own shortcomings, deepen the understanding of ES6 arrow function and Vue, value… It’s a long way to go, I see pain and joy (think)