【问题标题】:Vue.js - this.data not storing GET responseVue.js - this.data 不存储 GET 响应
【发布时间】:2017-04-03 03:40:06
【问题描述】:
<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <button v-on:click="sendTime">Load</button>
  <div v-for="user in users">
    <p>{{ user.username }}</p>
  </div>
</div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
  users: [
    { username: "billy" },
    { username: "ryan" }
  ],
},
methods: {
  sendTime : function () {
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    this.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}
})
</script>

</body>
</html>

console.log 返回 -

数组 [对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,还有 15 个……]

由于某种原因,我似乎无法将此数组分配给“this.data”?单击按钮时,唯一的变化是新的 console.log,但会显示 data 中的两个默认用户。任何帮助将不胜感激!

【问题讨论】:

  • 使用闭包或绑定或粗箭头函数为您的承诺回调捕获正确的“this”。

标签: javascript get vue.js axios


【解决方案1】:

您可以维护对 Vue 对象的引用,然后在回调中使用该引用。

methods: {
  sendTime : function () {
    var self = this;
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    self.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}

【讨论】:

    【解决方案2】:
    axios.get(...).then(function(response){
          this.users = response.data;
    }.bind(this))
    

    How to access the correct this inside a callback?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多