Vue js data()中的字段没有被调用第二个(help)函数初始化



我几乎没有任何使用vue js的经验。

我有两个函数loadComponentsOfUser()loadUserId(),因此loadComponentsOfUser()使用userID字段,必须由loadUserId()函数加载。

data() {
return { 
userId: ''
}
},
created() {
this.loadComponentsOfUser()
},
methods(): {
loadUserId() {
axios.get('getUserId').then(res => {
this.userId = res.data
}).catch(() => {
...
})
});
},
loadComponentsOfUser() {
this.loadUserId()
axios.get('users/' + this.userId).then(res => {
}).catch(() => {
...
})
});
}

loadUserId()函数正常工作并从服务器加载正确的值

但是当loadComponentsOfUser()被调用时,this。userId字段看起来没有初始化,axios得到一个空字段。

我的问题是为什么字段没有调用loadUserId()后初始化?

您需要等待响应,您可以使用asyncawait:

new Vue({
el: '#demo',
data() {
return { 
id: 1,
userId: '',
user: null
}
},
created() {
this.loadComponentsOfUser()
},
methods: {
async loadUserId() {
await axios.get('https://jsonplaceholder.typicode.com/users/' + this.id)
.then((res) => {
this.userId = res.data.id
})
.catch(() => {})
},
async loadComponentsOfUser() {
await this.loadUserId()
if(this.userId) {
axios.get('https://jsonplaceholder.typicode.com/users/' + this.userId)
.then(res => {
this.user = res.data
})
.catch(() => {})
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
<input type="number" v-model="id" /><button @click="loadComponentsOfUser">load</button>
{{ user }}
</div>

最新更新