vue實現(xiàn)頁面緩存功能
本文實例為大家分享了vue實現(xiàn)頁面緩存功能的具體代碼,供大家參考,具體內(nèi)容如下
主要利用keep-alive實現(xiàn)從列表頁跳轉到詳情頁,然后點擊返回時,頁面緩存不用重新請求資源。
一、在router里配置路由
在meta里定義頁面是否需要緩存
import Vue from "vue"; import Router from "vue-router"; // 避免到當前位置的冗余導航 const originalPush = Router.prototype.push Router.prototype.push = function push(location) { return originalPush.call(this, location).catch(err => err) } Vue.use(Router); export default new Router({ base: '', routes: [{ path: "/", name: "index", component: () => import("@/layout"), redirect: '/login', children: [ { path: 'dutySheet', name: 'dutySheet', component: () => import("@/pages/Dashboard/DutySheet") }, { path: 'searchWord', name: 'searchWord', component: () => import("@/pages/dailyReportManage/searchWord/index"), meta: { keepAlive: true // 需要緩存頁面 } }, // 匹配維護 { path: "troopAction", name: "troopAction", component: () => import("@/pages/Dashboard/TroopAction"), meta: { keepAlive: false// 不需要緩存 } }, ] }, ] });
二、配置APP.vue
使用keep-alive來進行緩存
<keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view>
三、點擊返回按鈕時調(diào)用this.$router.back()方法就可以了
// 返回 bacKBnt(){ this.$router.back() },
四、清除緩存
只針對跳轉到"exhibitionWord"或"exhibitionWeekWord"頁面才進行緩存,跳轉其他頁面不用緩存。
beforeRouteLeave(to, from, next) { if (to.name == 'exhibitionWord' || to.name == 'exhibitionWeekWord') { // 需要緩存的路由name from.meta.keepAlive = true next() }else{ from.meta.keepAlive = false next() } },
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
解決Idea、WebStorm下使用Vue cli腳手架項目無法使用Webpack別名的問題
這篇文章主要介紹了解決Idea、WebStorm下使用Vue cli腳手架項目無法使用Webpack別名的問題,需要的朋友可以參考下2019-10-10