[英]How To Ensure Vue Main Template Create Method Finishes Before Router-View Inner Template Create Method Starts
我有一個像這樣的主 Vue 模板的簡單設置:
<template>
<div>
[Other code here...]
<v-app style="overflow-y:hidden">
<router-view class="view"></router-view>
</v-app>
</div>
</template>
<script>
export default {
methods: {
created() {
//I NEED THIS CODE TO FINISH FIRST BEFORE ROUTER-VIEW
//TEMPLATE CREATED METHOD STARTS
await XxxService.xXXxXX()
.then((response) => {
localStorage.mySpecialVariable = yyyyy;
})
.catch(() => {
});
}
}
}
</script>
當前,當內部模板運行其create()
方法時,存在一種競爭條件,其中localStorage.mySpecialVariable
的值為null
。 有時它在那里,有時它不是,除非我運行該頁面兩次。
如何確保外部主模板代碼在任何事情繼續之前完成?
如果應用程序依賴於 API 響應,我會推遲安裝應用程序,直到收到響應:
// main.js
ApiService.fetch()
.then((response) => {
localStorage.mySpecialVariable = response.data.foo;
})
.catch((error) => {
console.error(error);
})
.then(() => {
// ok to mount
new Vue({/*...*/}).$mount();
})
因此,經過大量的測試和研究,我最終更新了 router.js 文件並在執行每條路由之前運行了我的代碼,這正是我需要它做的事情。
路由器.sj
router.beforeEach((to, from, next) => {
doTheThing(to.query.Token, next);
});
let doTheThing = async (token, next) => {
await apiService.doTheThing()
.then((response) => {
//Do Stuff Here
next();
})
.catch(() => {
});
}
所以發生的情況是,上面的 function 將在任何特定於頁面的代碼運行之前運行並完成,這是我要問的主要目標和問題。 我希望其他人會覺得這很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.