【问题标题】:can't assign fetch() data to vue property无法将 fetch() 数据分配给 vue 属性
【发布时间】:2021-09-29 14:52:58
【问题描述】:

我正在学习 fetch() 并且我已经设法从 Star Wars API 中获取一些数据。我想将返回的数据分配给一些 Vue 属性。但是它们会以 null 的形式返回。

默认情况下,我将它们设置为 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()
  }
})

【问题讨论】:

  • 实际上你给出的小提琴链接显示你将api数据分配给你的vue数据。你可以在 DOM 中看到它们。您在控制台日志中看到 null 是因为当您尝试接收数据时,它 console.logs 您的名字等于 null。

标签: vue.js


【解决方案1】:

您的代码实际上看起来(几乎)没问题。您唯一需要考虑的是,您在 getData 函数中使用 Promises。这意味着,您必须在 getData 函数中返回承诺,并在 Promise 解决后运行 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,这会使代码更具可读性。

【讨论】:

  • 非常感谢您的帮助@tho-masn
猜你喜欢
  • 2019-07-14
  • 2014-06-04
  • 2018-12-07
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多