vue.js - 无法将 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()
}
})
解决方案
您的代码实际上看起来(几乎)很好。您唯一需要考虑的是,您在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
,这使代码更具可读性。
推荐阅读
- javascript - 两个标签之间的网页抓取,使用cheerio
- java - 如何使用嵌套数组列表将 JLabel 项目发送到 Apache POI
- python - 如何正确创建 saved_model.pb?
- node.js - 在 mongodb 中加入两个集合
- javascript - 试图在 turfJS 中配置可配置属性的可配置属性?
- floating-point - clang/gcc 仅使用 -ffast-math 生成 fma;为什么?
- asp.net - 内容安全策略框架祖先在 IE 11 中不起作用
- amazon-web-services - AWS 应用程序负载均衡器公共 URL 不起作用
- typescript - 将装饰器应用于模块中的每个函数的函数类型
- c# - 会话过期时,Kendo 网格不会重定向到登录页面