vue实现页面缓存功能

2022-04-15 0 983

本文实例为大家分享了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()
      }
    },

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持NICE源码。

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript vue实现页面缓存功能 https://www.niceym.com/18674.html