Dmi*_*kov 46 javascript methods vue.js
我有以下代码:
{
data: function () {
return {
questions: [],
sendButtonDisable: false,
}
},
methods: {
postQuestionsContent: function () {
var that = this;
that.sendButtonDisable = true;
},
},
},
Run Code Online (Sandbox Code Playgroud)
调用sendButtonDisable时我需要更改为true postQuestionsContent().我发现只有一种方法可以做到这一点; 与var that = this;.
有更好的解决方案吗?
V. *_*bor 38
在内部方法中,如果您没有在其中定义另一个范围,您可以像这样访问您的数据:
this.sendButtonDisable = true;
Run Code Online (Sandbox Code Playgroud)
但是如果你在函数内部有一个范围,那么在vue中是函数开头的一个名为vm(代表视图模型)的变量的常见用法,然后在任何地方使用它,如:
vm.sendButtonDisable = false;
Run Code Online (Sandbox Code Playgroud)
完整的例子:
data: function () {
return {
questions: [],
sendButtonDisable : false
}
},
methods: {
postQuestionsContent : function() {
// This works here.
this.sendButtonDisable = true;
// The view model.
var vm = this;
setTimeout(function() {
// This does not work, you need the outside context view model.
//this.sendButtonDisable = true;
// This works, since wm refers to your view model.
vm.sendButtonDisable = true;
}, 1000);
}
}
Run Code Online (Sandbox Code Playgroud)
nil*_*ils 26
这取决于你怎么称呼你的postQuestionsContent方法(如果你异步调用它,你可能需要bind的this情况下).
在大多数情况下,您应该能够使用以下this.$data.YOURPROPNAME情况访问它this.$data.sendButtonDisable:
data: function () {
return {
questions: [],
sendButtonDisable : false
}
},
methods:
{
postQuestionsContent : function()
{
this.$data.sendButtonDisable = true;
}
}
Run Code Online (Sandbox Code Playgroud)
The*_*cle 10
试试这个
...
methods:
{
postQuestionsContent ()
{
this.sendButtonDisable = true;
}
}
Run Code Online (Sandbox Code Playgroud)
以上述方式注册您的方法应该可以解决问题.