正常写法是:
methods: {
getCode() {
this.$store.dispatch('getCode', this.phone)
}
}
问题:如果代码量大了,每一次使用Vue中的变量都需要加上前缀this
分析:我们可以在控制台中尝试打印this,可以看到:this打印出来是一个VueComponent的对象,包括了phone这个属性
methods: {
getCode() {
console.log(this)
this.$store.dispatch('getCode', this.phone)
}
}
打印结果如图:
可以看出,打印出的的对象包含了phone这个属性,我已经用红线标注出来
解决方案:
所以可以用es6的解构赋值把自己想要的属性解构出来,就可以直接用这个变量而不加this前缀了
methods: {
getCode() {
const { phone } = this //this是一个对象,包含了phone属性,左边解构出来给phone
this.$store.dispatch('getCode', phone) //可以直接用变量phone了
}
}