bus使用清除keepalive缓存

<template>
  <div id="app">
    <!-- <keep-alive>
      <router-view v-if="$route.meta.noCache"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.noCache"></router-view> -->

    <keep-alive>
      <router-view v-if="$route.meta.keepAlive" :key="fullPath"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  provide() {
    return {
      reload: this.reload
    }
  },
  computed: {
    fullPath() {
      // console.log(this.$route.fullPath);
      return this.$route.fullPath
    }
  },
  mounted() {
    // 注册监听全局的clearKeepAlive方法,可在其他组件中触发此方法
    this.$bus.$on('clearKeepAlive', this.clearKeepAlive)

    // 使用
    // this.$bus.emit("clearKeepAlive", path); // 清除缓存
  },
  methods: {
    // 根据fullUrl清除keepAlive
    clearKeepAlive(fullUrl) {
      // console.log('bus触发要清除的keepAlive', fullUrl);
      this.$children.forEach((item) => {
        if (item.$vnode.data.key == fullUrl) {
          console.log(item.$vnode.data.key)
          this._myDestory(item)
        }
      })
    },
    // 封装清除某个组件的keepAlive状态,并销毁
    _myDestory(keepAliveComponent) {
      // 你可以根据自己的业务更改此处的判断逻辑,酌情决定是否摧毁本层缓存。
      if (keepAliveComponent.$vnode && keepAliveComponent.$vnode.data.keepAlive) {
        if (
          keepAliveComponent.$vnode.parent &&
          keepAliveComponent.$vnode.parent.componentInstance &&
          keepAliveComponent.$vnode.parent.componentInstance.cache
        ) {
          if (keepAliveComponent.$vnode.componentOptions) {
            var key =
              keepAliveComponent.$vnode.key == null
                ? keepAliveComponent.$vnode.componentOptions.Ctor.cid +
                  (keepAliveComponent.$vnode.componentOptions.tag
                    ? `::${keepAliveComponent.$vnode.componentOptions.tag}`
                    : '')
                : keepAliveComponent.$vnode.key
            var cache = keepAliveComponent.$vnode.parent.componentInstance.cache
            var keys = keepAliveComponent.$vnode.parent.componentInstance.keys
            if (cache[key]) {
              if (keys.length) {
                var index = keys.indexOf(key)
                if (index > -1) {
                  keys.splice(index, 1)
                }
              }
              delete cache[key]
            }
          }
        }
      }
      keepAliveComponent.$destroy()
    },
    reload() {
      this.ifRouterAlive = false
      this.$nextTick(() => {
        this.ifRouterAlive = true
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
----------优化后  

        <keep-alive>
          <router-view
            v-if="$route.meta.keepAlive"
            :key="fullPath"
          ></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive"></router-view>

  computed: {
    fullPath() { 
      return this.$route.path;
    },}
  mounted() {
    // this.initWindow();
    // 注册监听全局的clearKeepAlive方法,可在其他组件中触发此方法
    this.$bus.$on("clearKeepAlive", this.clearKeepAlive);
    // 使用清除缓存
    // this.$bus.$emit("clearKeepAlive", path);
  },

       //获取实例进行清除
    clearKeepAlive(fullUrl) {
      if (this.$children && this.$children.length > 0) {
        this.$children.forEach((item) => {
          const { $vnode } = item
          if ($vnode && $vnode.data.key === fullUrl && $vnode.data.keepAlive) {
            this._myDestroy(item)
          }
        })
      }
    },
    _myDestroy(keepAliveComponent) {
      const { $vnode } = keepAliveComponent
      if ($vnode && $vnode.data.keepAlive && $vnode.parent && $vnode.parent.componentInstance) {
        const { parent } = $vnode
        const { key } = $vnode
        const { cache, keys } = parent.componentInstance
        if (cache && keys && cache[key] !== undefined) {
          for (const index of keys.entries()) {
            if (index[1] === key) {
              keys.splice(index[0], 1)
            }
          }
          delete cache[key]
          keepAliveComponent.$destroy()
        }
      }
    },

在vue2的main.js中代码是 import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import ElementUI from "element-ui"; import "@/permissions.js"; // 路由权限 import "element-ui/lib/theme-chalk/index.css"; import "element-ui/lib/theme-chalk/display.css"; import "@/styles/theme/index.css"; //换肤样式 import "@/styles/index.scss"; //全局公共样式 import Fragment from "vue-fragment"; // 可产生虚拟根节点 import ElTableEdit from "el-table-edit"; import "@/filters/index"; // 全局过滤器 import "@/directive/index"; // 注册全局指令 import MyElement from "@/components/my-element"; // ElementUI 组件覆盖 import ImageViewer from "@/components/ImageViewer/index"; // 图片预览组件 import "./console.js"; import mavonEditor from 'mavon-editor'; import 'mavon-editor/dist/css/index.css'; Vue.config.productionTip = false; Vue.use(ElementUI); Vue.use(Fragment.Plugin); Vue.use(ElTableEdit); Vue.use(MyElement); Vue.use(mavonEditor); Vue.prototype.$ELEMENT = { size: "medium", zIndex: 3000 }; Vue.prototype.$imageViewer = ImageViewer; ElementUI.Input.props.clearable = { type: Boolean, default: true }; ElementUI.Select.props.clearable = { type: Boolean, default: true }; ElementUI.Pagination.props.background = { type: Boolean, default: true }; ElementUI.Pagination.props.layout = { type: String, default: "total,prev,pager,next", }; new Vue({ router, store, render: function(h) { return h(App); }, beforeCreate(){ Vue.prototype.$bus=this } }).$mount("#app"); router下index.js中的代码是 import Vue from "vue"; import VueRouter from "vue-router"; import Layout from "@/layout"; import view from "./module/view"; import Pages from "./module/pages"; Vue.use(VueRouter); /* 对VueRouter原型链上的push、replace方法进行重写 为了解决某些情况下控制台报 ‘Uncaught (in promise) undefined’的问题 参考地址:https://github.com/vuejs/vue-router/issues/2881 / const originalPush = VueRouter.prototype.push; VueRouter.prototype.push = function push(location, onResolve, onReject) { if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject); return originalPush.call(this, location).catch((err) => err); }; /* 所有页面都应该是一级页面,或者说必须直接渲染到layout上,否则没有缓存 name 必须与组件name一致,用于路由缓存功能 permission 为布尔时表示需要权限,默认值应该为 false,待后端返回相应的地址后会自动改为 true / const routes = [ // { // path: "/login", // hidden: true, // component: () => // import(/ webpackChunkName: "login" */ "@/views/Login.vue"), // }, { path: "/", component: Layout, redirect: "/icon", meta: { keepAlive: true }, // 标记需要缓存的路由 children: [...view, ...Pages], }, { path: "/icon", component: () => import("@/views/Icon.vue"), meta: { keepAlive: true }, // 标记需要缓存的路由 }, { path: "/from", component: () => import("@/pages/form.vue"), meta: { keepAlive: true }, // 标记需要缓存的路由 }, ]; const router = new VueRouter({ mode: "history", // base: process.env.BASE_URL, routes, }); export default router; 引入的layout代码是 <template> <keep-alive> <Lock v-if="isLock" /> <el-container v-else class="container"> <Aside /> <div v-show="!isCollapse" class="drawer-bg" @click="setCollapse(!isCollapse)" ></div> <el-container> <!-- <el-header class="el-header" height="auto"> <Header /> <Tabs /> </el-header> --> <el-main class="main"> <WaterMark :height="36" :width="100" image=""> <keep-alive :include="include"> <router-view /> </keep-alive> </WaterMark> </el-main> <!-- <el-backtop target=".main"></el-backtop> --> </el-container> </el-container> </keep-alive> </template> <script> import Aside from "./Aside"; // import Header from "./Header"; // import Tabs from "./Tabs"; import Lock from "./Lock"; import WaterMark from "@/components/WaterMark"; export default { components: { Aside, Lock, WaterMark }, computed: { //控制侧边栏展开收起状态 isCollapse() { return this.$store.state.layout.isCollapse; }, include() { return this.$store.getters.include; }, isLock() { return this.$store.state.lock.isLock; }, }, methods: { // 控制侧边栏导航 setCollapse(collapse) { this.$store.commit("setCollapse", collapse); }, }, }; </script> <style scoped lang="scss"> .container { position: relative; .el-header { padding: 0 !important; } .el-main{ padding: 0px; } .drawer-bg { display: none; } @media screen and (max-width: 1200px) { .drawer-bg { display: block; width: 100%; height: 100vh; position: absolute; top: 0; background: #000; opacity: 0.3; z-index: 1999; } } } .dark-theme .container .main { background-color: $dark-layout-main; } </style> 如何在路由中加入 缓存
07-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值