Vue 手动清除缓存

359 阅读1分钟

Vue 手动清除缓存

Vue2 手动清除缓存

Vue2 切换标签添加缓存

<transition name="fade-transform" mode="out-in">
            <keep-alive :max="viewMaxLength">
              <!-- 发布模式添加key,防止新增编辑重复,开发模式去掉key,用于热更新 -->
              <router-view ref="routerView" :key="key" />
              <!-- <router-view v-if="isProMode" :key="key" />
              <router-view v-else /> -->
            </keep-alive>
          </transition>

Vue2 关闭标签清除缓存

关闭标签主动调用 changeTag方法

 changeTag() {
      /**
       * @param {Object} cache:类数组对象,存放缓冲的路由组件,键值对形,key为路由路径,value为路由组件Vnode
       * @param {Array} keys:数组,存放缓冲的路由组件的key,即路由路径
       * @param {String} key:字符串,路由组件的key,指定要删除的路由组件key值
       */
      if (!this.routerView?.$vnode?.parent) return;
      const { cache, keys } = this.routerView?.$vnode.parent.componentInstance;

      const viewKeys = TagsViewStore.visitedViews.map((view: any) => view.path?.toLocaleLowerCase());

      let transtionStr = '';
      if (keys[0]?.indexOf('-')) {
        let arr = keys[0].split('-/');
        arr[arr.length - 1] = '';
        transtionStr = arr.join('-')?.toLocaleLowerCase();
      }

      Object.keys(cache).forEach((cacheKey: string) => {
        let key = cacheKey;

        if (transtionStr) {
          key = cacheKey.replace(transtionStr, '')?.toLocaleLowerCase();
        }

        if (!viewKeys.includes(key)) {
          cache[cacheKey]?.componentInstance.$destroy();
          delete cache[cacheKey];
          keys.splice(keys.indexOf(cacheKey), 1);
          // cacheView.$vnode.componentInstance.$destroy();
          // cacheKeys[cacheKey]--;
        }
        // else {
        //   if (cacheKeys[cacheKey] > 1) {
        //     // cacheView.$vnode.componentInstance.$destroy();
        //     cacheKeys[cacheKey]--;
        //   }
        // }
      });

Vue3 手动清除缓存

Vue3 换标签缓存

	<router-view ref="routerviewRef" v-slot="{ Component }">
						<transition name="fade-transform" mode="out-in">
							<keep-alive ref="keepaliveRef">
								<component :is="Component" :key="key" />
							</keep-alive>
						</transition>
					</router-view>

Vu3关闭标签清除缓存

vue3 获取keepAlive中 __v_cache ,只在开发环境中可以获取,因此需要将 __v_cache 放出

const keepaliveRef = ref()

emits.on('tagChange', () => {
	// console.log('tagChange')
	const tagKeys = store.tabsStore.visitedViews.map((item: any) => item.path)

	// 开发环境可获取 __v_cache,或者修改源码将 __v_cache 放出展示
	const cache = keepaliveRef.value.$?.__v_cache

	cache?.forEach((item: any) => {
		if (!tagKeys.includes(item.key)) {
			cache.delete(item.key)
		}
	})
})

添加 config/removeDEV.js,将 __v_cache 中if判断添加注释,打包时先使用 node ./config/removeDEV.js 然后在进行 npm run build

const path = require('path')
const fs = require('fs')
// 修改源文件,将 __v_cache 在生产环境中放出
try {
	const vue_bundler_file = path.resolve(__dirname, '../node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js')
	//使用同步读取文件
	let data = fs.readFileSync(vue_bundler_file, 'utf8')
	//如果未添加过
	if (data.indexOf('//__v_cache') < 0) {
		console.log('正在修改源码文件:', vue_bundler_file)
		//先找到__v_cache变量的位置
		let index = data.indexOf('__v_cache')
		if (index >= 0) {
			// 继续往前找if关键字
			index = data.lastIndexOf('if ', index)
			if (index >= 0) {
				//从上一个位置开始
				index -= 1
				//然后放一个注释
				const comment = ' //__v_cache '
				//然后拼接
				data = data.substring(0, index) + comment + data.substring(index)

				//继续往后找下一个大括号 }
				index = data.indexOf('}', index)
				if (index >= 0) {
					//从上一个位置开始
					index -= 1
					//然后拼接
					data = data.substring(0, index) + comment + data.substring(index)
				}

				fs.writeFileSync(vue_bundler_file, data, 'utf8')
			}
		}
	}
} catch (er) {
	console.error(er.message)
}