<script src='_js/vue.2.6.11.js'></script>
<div id="app">
<h1>{{ email }}</h1>
<h1>{{ email[reportID]</h1>
<hr>
<button @click='makeItGo'>CLICK</button>
</div>
<script>
var vm = new Vue ({
el: '#app',
data: {
email: [],
reportID: 40,
info: 'this is info',
},
methods: {
makeItGo() {
vm.email.push(vm.reportID);
vm.email[reportID] = info; <-- this doesn't work. WHY?
vm.email[reportID].push(info); <-- this doesn't work either. WHY?
}
},
});
</script>
这将产生以下错误:
[Vue warn]: Error in v-on handler: "ReferenceError: reportID is not defined" (found in <Root>) ReferenceError: "reportID is not defined" makeItGo http://localhost/project/test.php line 669 > scriptElement:27 invokeWithErrorHandling http://localhost/project/_js/vue.2.6.11.js line 669 > scriptElement:1863 invoker http://localhost/project/_js/vue.2.6.11.js line 669 > scriptElement:2188 _wrapper http://localhost/project/_js/vue.2.6.11.js line 669 > scriptElement:7547
这是令人沮丧的地方:为什么它如此明确地声明'reportID'是未定义的。为什么会直接调用它(vm.email与电子邮件),而不像我期望的那样绕过任何范围界定问题(这似乎是问题所在)?在PHP中,这只是不会发生,所以我很困惑。好。由于人们不断陷入与问题无关的事情的困扰,因此完成了彻底的改造。所以我把它归结为最小的精髓:
this
let that = this;
然后在整个方法中使用that
,而不是this
。这样,您可以保留每种方法的作用域。