Javascript Vue 从方法中访问数据的方式是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36176073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is Vue way to access to data from methods?
提问by Dmitry Bubnenkov
I have the following code:
我有以下代码:
{
data: function () {
return {
questions: [],
sendButtonDisable: false,
}
},
methods: {
postQuestionsContent: function () {
var that = this;
that.sendButtonDisable = true;
},
},
},
I need to change sendButtonDisable
to true when postQuestionsContent()
is called. I found only one way to do this; with var that = this;
.
我需要sendButtonDisable
在postQuestionsContent()
被调用时更改为 true 。我只找到了一种方法来做到这一点;与var that = this;
.
Is there a better solution?
有更好的解决方案吗?
回答by V. Sambor
Inside methods if you don't have another scope defined inside, you can access your data like that:
内部方法如果您没有在内部定义另一个范围,您可以像这样访问您的数据:
this.sendButtonDisable = true;
but if you have a scope inside the function then in vue is a common usage of a variable called vm
(stands for view model) at the beginning of the function, and then just use it everywhere like:
但是如果你在函数内部有一个作用域,那么在 vue 中是一个在函数开头被称为vm
(代表视图模型)的变量的常见用法,然后在任何地方使用它,例如:
vm.sendButtonDisable = false;
An example of vm
can be seen in the Vue official documentationas well.
vm
在Vue 官方文档中也可以看到一个示例。
complete example:
完整示例:
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);
}
}
回答by nils
It depends on how you call your postQuestionsContent
method (if you call it asynchronously, you might need to bind
the this
context).
这取决于你怎么称呼你的postQuestionsContent
方法(如果你异步调用它,你可能需要bind
的this
情况下)。
In most cases, you should be able to access it using this.$data.YOURPROPNAME
, in your case this.$data.sendButtonDisable
:
在大多数情况下,您应该能够使用 访问它this.$data.YOURPROPNAME
,在您的情况下this.$data.sendButtonDisable
:
data: function () {
return {
questions: [],
sendButtonDisable : false
}
},
methods:
{
postQuestionsContent : function()
{
this.$data.sendButtonDisable = true;
}
}
回答by The Oracle
Try this instead
试试这个
...
methods:
{
postQuestionsContent ()
{
this.sendButtonDisable = true;
}
}
Registering your methods in the above manner should resolve the issue.
以上述方式注册您的方法应该可以解决问题。