背景
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);不知道有咩有幫大家理清思路,有問題可以留言,以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選