首页 > 解决方案 > 如何使用获取的数据更新 Vue 组件的属性

问题描述

Vue.component('test', {
  template: `some html`,
  data() {
    {
      return {
        somedata: 'hey, starting!'
      }
    }
  },
  methods: {
    fetchdata: function fetchdata() {
      fetch('http://localhost:5000/getmesome')
        .then(response => response.json()).then(data => this.somedata = data
        );
    }
  }, created() {
    this.fetchdata();
    console.log(this.somedata); //returns 'hey starting' not the fetched data.
  }
});

如代码注释所示,这不是用获取的数据刷新属性。我该怎么做?

谢谢。

标签: vue.js

解决方案


fetchdata()将在请求仍在进行时立即返回,因为它是异步操作。console.log(this.somedata)将在获取操作完成之前执行。

这是一个基本的异步误解;我建议您阅读异步 JavaScript 主题(promisesasyncawait等)。

这些解决方案中的任何一个都可以工作:

methods: {
  fetchdata() {
    return fetch('http://localhost:5000/getmesome')
      .then(response => response.json())
      .then(data => this.somedata = data);
  }
},

created() {
  this.fetchdata()
    .then(() => console.log(this.somedata));
}
methods: {
  async fetchdata() {
    const res = await fetch('http://localhost:5000/getmesome');
    const data = await res.json();
    this.somedata = data;
  }
},

async created() {
  await this.fetchdata();
  console.log(this.somedata);
}

推荐阅读