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

JavaScript

LEY老丝

2020-03-11

我有以下代码:

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

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

我需要sendButtonDisablepostQuestionsContent()调用更改为true 我发现只有一种方法可以做到这一点。var that = this;

有更好的解决方案吗?

第620篇《Vue从方法访问数据的方式是什么?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
西门十三LEY 2020.03.11

试试这个

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

以上述方式注册您的方法应该可以解决问题。

伽罗Tony小卤蛋 2020.03.11

在方法内部,如果没有在内部定义其他范围,则可以这样访问数据:

this.sendButtonDisable = true; 

但是,如果您在函数内部具有作用域,则在函数开始时,通常会使用一个称为vm(代表view model)的变量,然后将其随处使用,例如:

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); 
  }
}
Tony达蒙Mandy 2020.03.11

这取决于你怎么称呼你的postQuestionsContent方法(如果你异步调用它,你可能需要bindthis情况下)。

在大多数情况下,你应该能够使用来访问它this.$data.YOURPROPNAME,你的情况this.$data.sendButtonDisable

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

  },

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android