vue實現頁面緩存功能

本文實例為大傢分享瞭vue實現頁面緩存功能的具體代碼,供大傢參考,具體內容如下

主要利用keep-alive實現從列表頁跳轉到詳情頁,然後點擊返回時,頁面緩存不用重新請求資源。

一、在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>

三、點擊返回按鈕時調用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()
      }
    },

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: