Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Vue way to access to data from methods?

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?

like image 638
Dmitry Bubnenkov Avatar asked Mar 23 '16 10:03

Dmitry Bubnenkov


People also ask

What is data method in VueJS?

js data() we defined collection of logic and stored in component using vue. js we can access data Node. jsassociated with a vue instance. Components are reusable as many times as per requirement. But each time it uses a separate component and also creates a new instance.

How does Vue pass values between components?

VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!


1 Answers

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; 

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

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);    } } 
like image 108
V. Sambor Avatar answered Sep 23 '22 16:09

V. Sambor