我正在处理范围问题,但无法使用解决方法 let that = this;
我想更改变量 error
。在这里你是CODEPEN Example
HTML
<div id="app" class="container">
{{error}}
<br>
<button type="button" @click="change()">Change Variable Error</button>
</div>
JS
var demo = new Vue({
el: '#demo',
data:{
error: "a",
item: {
foo: function(){
alert('Change!');
this.error = "Something went wrong!";
}
}
},
methods:{
change(){
this.item.foo();
}
}
});
谢谢!
最佳答案
这不是 vue 问题,而是 javascript“THIS”问题。您可以在方法中使用此代码获得您想要的内容。
change() {
this.item.foo.bind(this)();
}
在函数 foo 中,有 this.error
。但是这个 this
并没有绑定(bind)到 vue 实例的范围。因此,您应该在调用之前将其绑定(bind)到此范围。
另外,我不建议您改变数据属性中的状态。它可能是反模式。
关于javascript - 处理 VueJS 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52042928/