首页 > 解决方案 > 无法将 fetch() 数据分配给 vue 属性

问题描述

我正在学习 fetch() 并且我已经设法从 Star Wars API 中获取了一些数据。我想将返回的数据分配给一些 Vue 属性。然而,他们回来为空。

默认情况下,我将它们设置为 null,但是一旦开始获取,值就不会更新。有谁知道为什么?我一直在关注本教程https://scotch.io/@bedakb/lets-build-type-ahead-component-with-vuejs-2-and-fetch-api并以相同的方式分配了我的数据。

https://jsfiddle.net/Ltwen65g/

JS:

new Vue({
  el: "#app",
  data: {
        name: null,
    height: null
  },
  methods: {
        getData() {
        fetch('https://swapi.dev/api/people/1')
          .then((res) => res.json())
          .then((data) => {
            console.log(data);
            this.name = data.name;
            this.height = data.height;
          })
    },
    consoleLog() {
        console.log(this.name, this.height);
    }
  },
  mounted() {
        this.getData()
    this.consoleLog()
  }
})

标签: vue.js

解决方案


您的代码实际上看起来(几乎)很好。您唯一需要考虑的是,您在getData函数中使用 Promises。这意味着,您必须在函数中返回Promise 并在 Promise 解决后getData运行该函数,如下所示:consoleLog

https://jsfiddle.net/93z4wrba/3/

new Vue({
  el: "#app",
  data: {
    name: null,
    height: null
  },
  methods: {
    getData() {
      return fetch('https://swapi.dev/api/people/1')
        .then((res) => res.json())
        .then((data) => {
          console.log(data);
          this.name = data.name;
          this.height = data.height;
        })
    },
    consoleLog() {
      console.log(this.name, this.height);
    }
  },
  created() {
    this.getData()
      .then(() => {
        this.consoleLog()
      })
  }
})

也许考虑切换到async/await,这使代码更具可读性。


推荐阅读