What is Vue way to access to data from methods?

后端 未结 3 1152
攒了一身酷
攒了一身酷 2021-02-01 12:12

I have the following code:

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

  methods: { 
    postQuestions         


        
相关标签:
3条回答
  • 2021-02-01 12:32

    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); 
      }
    }
    
    0 讨论(0)
  • 2021-02-01 12:36

    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;
         }
      }
    
    0 讨论(0)
  • 2021-02-01 12:47

    Try this instead

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

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

    0 讨论(0)
提交回复
热议问题