案例
<script>
export default {
data() {
return {
// 表单
form: {
input: ''
}
}
},
...
methods: {
// 重置表单方法
retset() {
this.form = this.$options.data().form;
}
},
...
}
</script>
如果实际到重置之后涉及到调用方法,
export default {
props: {
P: Object
},
data () {
return {
A: {
a: this.methodA
},
B: this.P
};
},
methods: {
resetData () { // 更新时调用
Object.assign(this.$data, this.$options.data()); // 有问题!!!
},
methodA () {
// do sth.
},
methodB () { // 通过用户操作调用
this.A.a && this.A.a(); // this.A.a is undefined, this.B is undefined!!!
}
}
}
请更改为:
resetData () { // 更新时调用
Object.assign(this.$data, this.$options.data.call(this));
}
原因:
构建Vue实例的时候,构造函数和自定的属性是定义在$options下面,而方法却不是
总结
data()中若使用了this来访问props或methods,在重置** d a t a ∗ ∗ 时 , 注 意 ∗ ∗ t h i s . data**时,注意**this. data∗∗时,注意∗∗this.options.data()的this指向,最好使用this.$options.data.call(this)**。