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

新手上路,请多包涵

我有以下代码:

 {
  data: function ()  {
    return {
      questions: [],
      sendButtonDisable: false,
    }
  },

  methods: {
    postQuestionsContent: function () {
      var that = this;
      that.sendButtonDisable = true;
    },
  },
},

当调用 postQuestionsContent() 时,我需要将 sendButtonDisable 更改为 true。我发现只有一种方法可以做到这一点;与 var that = this;

有更好的解决方案吗?

原文由 Dmitry Bubnenkov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 598
1 个回答

如果您没有在内部定义另一个范围,则在内部方法中,您可以像这样访问您的数据:

 this.sendButtonDisable = true;

但是如果你在函数内部有一个作用域,那么在 vue 中,在函数的开头通常使用一个名为 vm (代表 视图模型)的变量,然后在任何地方都使用它,比如:

 vm.sendButtonDisable = false;

vm 的例子也可以在 Vue官方文档 中看到。

完整的例子:

 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);
  }
}

原文由 V. Sambor 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题