数据不会在 vue js 中更新

新手上路,请多包涵

我有一个像这样的简单表格

<form @submit.prevent="getSummary">
    <input type="text" v-model="userAcccount" placeholder="Enter Account
    Number">
    <button type="submit" class="btn btn-xs btn-default">Submit</button>
</form>

我在vue中的方法对象中的getSummary方法是这样的

methods: {
        getSummary () {
            axios.get('core/handle.php', {
                params: {
                  accountNumber: this.userAcccount
                }
              })
              .then(function (response) {
                this.userData = response.data;
                console.log(this.userData);
              })
              .catch(function (error) {
                alert(error);
            });
        }
    }

我的数据对象包含

data: {
        userAcccount: '',
        userData: []
    },

我正在尝试使用 axios 的响应更新 userData,然后使用它来填充表以进行测试我刚刚尝试了这个

<span v-if="userData.length > 0">
      some data
</span>
<span v-else>
      data not found
</span>

console.log 显示 userData 已更新,但上面的这段代码没有改变。

原文由 Dapo Michaels 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 292
2 个回答

您无法通过 this 在您的 then 函数中访问虚拟机。您可以通过三种方式解决此问题:

  1. 显式绑定外部 this 作为函数的执行上下文(ES5 函数有自己的 this):
    .then(function (response) {
       this.userData = response.data;
       console.log(this.userData);
   }.bind(this))

  1. this 上下文存储在局部变量中,例如 selfthat
    getSummary () {
     const self = this;
     axios.get('core/handle.php', {
       params: {
         accountNumber: this_.userAcccount
       }
     })
     .then(function (response) {
       self.userData = response.data;
       console.log(self.userData);
     })
     .catch(function (error) {
       alert(error);
     });
   }

  1. 使用没有自己的 ES6 箭头函数 this
    .then(response => {
     this.userData = response.data;
     console.log(this.userData);
   })

Javascript 中 this 的概念与许多其他编程语言有很大不同,因为它描述了函数的执行上下文。这不是一个容易理解的概念,但这帮助我理解了它:

http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

作为参考,MDN 始终是一个不错的去处:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

原文由 connexo 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 ES6 箭头函数,您可以通过稍微重写来访问回调中的响应,如下所示:

 .then(response => {
    this.userData = response.data;
    console.log(this.userData);
})

这是因为您当前正在使用 this 到达 axios 请求上下文,这显然是空的,因为 userData 不在您的范围内。通过使用箭头函数语法,您可以访问 userData 所在的父组件。

原文由 sundeqvist 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏