从方法访问数据的Vue方式是什么?

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)

  • 这个答案对于vue新手(voobs?)非常有用。Vue 2文档甚至在以下页面上使用** vm = this **:https://vuejs.org/v2/guide/computed.html#Watchers但是通过文档很容易监督此阅读。 (3认同)
  • 为“voobs”而奋斗! (2认同)
  • 另请注意,如果我们在“methods”中使用箭头函数而不是普通函数,它将不起作用 (2认同)
  • 发现此内容的人请注意:如果您使用 lambda 表示法 `this` 将不起作用,因此请使用 `function(){}` (2认同)

nil*_*ils 26

这取决于你怎么称呼你的postQuestionsContent方法(如果你异步调用它,你可能需要bindthis情况下).

在大多数情况下,您应该能够使用以下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)

  • 嗨@TheOracle问题和aswer在vue 0.x版本的领域是有效的.2.x应该在没有`$ data`的情况下正常工作. (4认同)
  • 一些原因这不起作用.我认为社区应该审查这个问题. (2认同)
  • 我正在使用2.5.17遇到此问题。可能必须将其报告为错误,但是$ data可以工作。 (2认同)

The*_*cle 10

试试这个

...
methods: 
{ 
   postQuestionsContent ()
   {
      this.sendButtonDisable = true;
   }
}
Run Code Online (Sandbox Code Playgroud)

以上述方式注册您的方法应该可以解决问题.

  • 你能解释一下这是怎么回事吗?为什么这有效? (3认同)
  • @UmairA。来自 Vue 文档:`请注意,您不应该使用箭头函数来定义方法(例如 plus: () => this.a++)。原因是箭头函数绑定了父上下文,因此这不会是您期望的 Vue 实例,并且 this.a 将是未定义的。`此处:https://vuejs.org/v2/api/#methods (2认同)