vue.js - 如何使用获取的数据更新 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.
}
});
如代码注释所示,这不是用获取的数据刷新属性。我该怎么做?
谢谢。
解决方案
fetchdata()
将在请求仍在进行时立即返回,因为它是异步操作。console.log(this.somedata)
将在获取操作完成之前执行。
这是一个基本的异步误解;我建议您阅读异步 JavaScript 主题(promisesasync
和await
等)。
这些解决方案中的任何一个都可以工作:
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);
}
推荐阅读
- javascript - 车把多选助手
- python - 将 MongoAlchemy 模型转换为 PyMongo
- spring-boot - H2 不使用 Spring Boot 将我的 jsp Web 表单更新到我的简单数据库
- swift - 视图第二次没有出现 [Swift]
- sql-server - 如何在 SQL Server 中禁用多线程?
- ruby-on-rails - Why is Ruby not updating after updating with Ruby Installer?
- python-3.x - 按列连接两个数据框
- excel - Excel:通过从另一个选项卡中引入相应的单元格来填充新列
- algorithm - 为 sha256 创建 2 路地图。
- java - while 循环会在一段时间后停止执行吗?