使用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);
不知道有咩有幫大家理清思路,有問題可以留言,
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com