vue页面缓存 vue实现页面缓存功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue页面缓存 vue实现页面缓存功能

无月大大   2021-10-28 我要评论
想了解vue实现页面缓存功能的相关内容吗,无月大大在本文为您仔细讲解vue页面缓存的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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()
      }
    },

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们