index頁面:首頁品牌入口
list頁面:商品列表頁面
product頁面:商品詳情頁面
從index頁面進入list的時候要刷新頁面,從product頁面返回list的時候不須要刷新頁面
因此list使用了keep-alive的屬性,keepAlive設置爲true,可是開發過程當中發現一個問題,
從product返回到list的時候,列表頁面不是正確的品牌列表,而是以前一次點擊的品牌列表。
因爲每一個人遇到關於keep-alive請求數據不正確的問題不一樣,這裏就直接說個人解決辦法。
但願能給你們一個思路。vue
不少人都會經過修改keepAlive來改變keep-alive,我嘗試後仍是不行,就換了個思路緩存
不使用keep-alive beforeRouteEnter --> created --> mounted --> destroyed 使用keep-alive beforeRouteEnter --> created --> mounted --> activated --> deactivated
先掃盲,多少人和我都不知道上面的知識,在keep-alive的頁面中,能夠在 activated獲取this.$route.params的參數app
避開了設置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.jsfetch
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 ̄)づ╭❤~this