我有一個 Vue 應用程式。我想根據用戶 ID 檢索條目(從資料庫中)。我在 Vue 中有以下方法:
export default {
name: 'Entries',
data() {
return {
userid: null
};
},
methods: {
getEntries() {
this.getUserID();
console.log("userid getEntries: " this.userid);
axios.get('/entries', this.userid)
.then((res) => {
this.entries = res.data;
console.log(this.entries);
})
.catch((error) => {
console.error(error);
});
},
getUserID() {
axios.get('/userid')
.then((res) => {
this.userid = res.data;
console.log("userid getUserId: " this.userid );
})
.catch((error) => {
console.error(error);
});
},
},
created() {
this.getEntries();
}
};
在該getEntries方法中,我立即呼叫該getUserID函式。我假設這會將變數設定為userid從getUserID方法中檢索到的值。
相反,我在瀏覽器控制臺中得到以下輸出,完全按照這個順序:
userid getEntries: null
userid getUserId: user_a
為什么它首先列印getEntries函式的控制臺輸出?如果它首先執行該getUserID方法,為什么它是空的?
我該如何更改以便 axios 呼叫/entries可以傳遞用戶 ID。
uj5u.com熱心網友回復:
axios 呼叫是異步的,如果你需要在呼叫其他任何東西之前填充用戶 ID,那么你應該在呼叫其他任何東西之前填充,在安裝/創建中。
然后你可以通過觀察者對它的變化做出反應。您可以在 getUserID 呼叫決議時呼叫 getEntries ,但它很臟并且耦合了兩種方法。
并且不要忘記分配entries資料。
這將起作用:
export default {
name: 'Entries',
data() {
return {
userid: null,
entries: []
};
},
watch: {
userid (v) {
if (v) this.getEntries()
}
},
mounted() {
this.$nextTick(this.getUserID)
},
methods: {
getEntries() {
console.log("userid getEntries: " this.userid);
axios.get('/entries', this.userid)
.then((res) => {
this.entries = res.data;
console.log(this.entries);
})
.catch((error) => {
console.error(error);
});
},
getUserID() {
axios.get('/userid')
.then((res) => {
this.userid = res.data;
console.log("userid getUserId: " this.userid);
})
.catch((error) => {
console.error(error);
});
}
}
};
使用異步/等待
export default {
name: 'Entries',
data() {
return {
userid: null,
entries: []
};
},
watch: {
userid (v) {
if (v) this.getEntries()
}
},
mounted() {
this.$nextTick(this.getUserID)
},
methods: {
async getEntries() {
try {
const { data } = await axios.get('/entries', this.userid)
this.entries = data;
} catch (error) {
console.error(error);
}
},
async getUserID() {
try {
const { data } = await axios.get('/userid')
this.userid = data;
} catch (error) {
console.error(error);
}
}
}
};
uj5u.com熱心網友回復:
由于getUserId是異步的,它不會立即回傳。因此,您需要等待它回傳才能繼續。這可以使用then但是,嵌套的 Promise 使用起來有點不愉快。一個更簡單的選擇是使用async/await:
async getEntries() {
await this.getUserID();
console.log("userid getEntries: " this.userid);
axios.get('/entries', this.userid)
.then((res) => {
this.entries = res.data;
console.log(this.entries);
})
.catch((error) => {
console.error(error);
});
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380335.html
標籤:Vue.js
下一篇:Nuxt存盤getter不起作用,賦予有效載荷的ID不是整數 錯誤:[vuex]不要在突變處理程式之外改變vuex存盤狀態
