vue keep-alive請求資料
阿新 • • 發佈:2018-12-16
背景
index頁面:首頁品牌入口
list頁面:商品列表頁面
product頁面:商品詳情頁面
從index頁面進入list的時候要重新整理頁面,從product頁面返回list的時候不需要重新整理頁面
所以list使用了keep-alive的屬性,keepAlive設定為true,但是開發過程中發現一個問題,
從product返回到list的時候,列表頁面不是正確的品牌列表,而是之前一次點選的品牌列表。
由於每個人遇到關於keep-alive請求資料不正確的問題不同,這裡就直接說我的解決辦法。
希望能給大家一個思路。
解決辦法
很多人都會通過修改keepAlive來改變keep-alive,我嘗試後還是不行,就換了個思路
鉤子函式的執行順序
不使用keep-alive
beforeRouteEnter --> created --> mounted --> destroyed
使用keep-alive
beforeRouteEnter --> created --> mounted --> activated --> deactivated
先掃盲,多少人和我都不知道上面的知識,在keep-alive的頁面中,可以在 activated獲取this.$route.params的引數
避開了設定keepAlive導致product返回的時候資料不對,當頁面進入list的時候都是快取狀態,然後再通過是不是由index進入來判斷是否執行activated裡的函式,
list.vue
beforeRouteEnter(to, from, next) { //判斷從index頁面進入,將list的isBack設定為true //這樣就可以請求資料了 if (from.name == 'index') { to.meta.isBack = true; } next(); }, activated: function () { if (this.$route.meta.isBack || this.isFirstEnter) { //清理已有商品列表的資料,重新請求資料,如果不清除的話就會有之前的商品快取,延遲顯示最新的商品 this.proData = []; //請求資料 this.fetchData(); } //重新設定當前路由的isBack this.$route.meta.isBack = false; //重新設定是否第一次進入 this.isFirstEnter = false; }, mounted: function () { //如果是第一次進入,或者重新整理操作的話,也請求資料 this.isFirstEnter = true; },
router.js
const appRouter = {
mode: "history",
base: "/m/",
routes: [
{
path: "",
redirect: "/index"
},
{
path: "/index",
name: "index",
component: Index,
meta: {
keepAlive: true
}
},
{
path: "/list",
name: "list",
component: List,
meta: {
keepAlive: true,
isBack: false //isback是true的時候請求資料,或者第一次進入的時候請求資料
}
},
{
path: "/product/:id",
name: "product",
component: Product,
meta: {
keepAlive: false
}
}
]
};
Vue.use(Router);
export default new Router(appRouter);
不知道有咩有幫大家理清思路,如果有什麼疑問可以留言交流,(づ ̄3 ̄)づ╭❤~