从方法访问数据的Vue方式是什么? [英] What is Vue way to access to data from methods?

查看:109
本文介绍了从方法访问数据的Vue方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

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

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

I need to change sendButtonDisable to true when postQuestionsContent() is called. I found only one way to do this; with var that = this;.

有更好的解决方案吗?

推荐答案

如果你没有在里面定义另一个范围,你可以访问你的数据:

Inside methods if you don't have another scope defined inside, you can access your data like that:

this.sendButtonDisable = true; 

但是如果你在函数中有一个范围,那么在vue中是一个名为<的变量的常见用法code> vm (代表查看模型)在函数的开头,然后在任何地方使用它,如:

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:

vm.sendButtonDisable = false;

可以看到 vm 的示例 Vue官方文档

An example of vm can be seen in the Vue official documentation as well.

完整示例:

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

这篇关于从方法访问数据的Vue方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆