What is Vue way to access to data from methods?

2019-03-17 09:56发布

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;.

Is there a better solution?

3条回答
Explosion°爆炸
2楼-- · 2019-03-17 10:11

It depends on how you call your postQuestionsContent method (if you call it asynchronously, you might need to bind the this context).

In most cases, you should be able to access it using this.$data.YOURPROPNAME, in your case this.$data.sendButtonDisable:

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

  },

  methods: 
  { 
     postQuestionsContent : function()
     {
        this.$data.sendButtonDisable = true;
     }
  }
查看更多
Viruses.
3楼-- · 2019-03-17 10:30

Try this instead

...
methods: 
{ 
   postQuestionsContent ()
   {
      this.sendButtonDisable = true;
   }
}

Registering your methods in the above manner should resolve the issue.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-03-17 10:31

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:

vm.sendButtonDisable = false;

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 a the outside context view model.
      //this.sendButtonDisable = true;

      // This works, since wm refers to your view model.
      vm.sendButtonDisable = true;
    }, 1000); 
  }
}
查看更多
登录 后发表回答