不要在选项属性或回调上使用箭头函数,比如created: () => console.log(this.a)vm.$watch('a', newValue => this.myMethod())。因为箭头函数并没有thisthis会作为变量一直向上级词法作用域查找,直至找到为止,经常导致Uncaught TypeError: Cannot read property of undefinedUncaught TypeError: this.myMethod is not a function之类的错误。

错误示范:

1
2
3
4
5
6
7
8
9
10
11
12
13
<el-button type="primay" icon="el-icon-plus" @click="add"></el-button>
<p>{{count}}</p>
<script>
const app = new Vue({
// ...
data: {
count: 1
},
methods: {
add: () => this.count++
}
});
</script>

正确示范:

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
const app = new Vue({
// ...
methods: {
add: function () {
this.count++
},
minus() {
this.count--
}
}
});
</script>