在created中异步请求数据,在mounted中获取不到数据。
// template
<div>{{ title }}</div>
// js
async created() {
await this.getTitle();
console.log(this.title); // 有数据
},
mounted() {
console.log(this.title); // 没有数据
}
methods:{
getTitle(){
this.$https.get('接口地址')
.then((res) => {
this.title = res.data.title
})
}
}
解决办法:
利用watch监听数据,然后再获取数据。
watch: {
title: {
handler(newVal: any) {
this.title = newVal
}
}
}