当前位置:网站首页>Explain Vue's plan to clean up keepalive cache in time
Explain Vue's plan to clean up keepalive cache in time
2022-07-05 14:25:00 【1024 questions】
demand
reflection
Try
1. Manual operation keep-alive Component's cache Array
2. exclude Dafa is good
Demo
demandSingle page application , The user enters the form filling page , The form content needs to be initialized , The filling process may involve operations such as map point selection or list selection , You need to go to the new page to select and recall the display .
At this time, we need to cache the form filling page instance , When you exit the form and fill in or submit the contents of the form , You need to destroy the current form instance , Re initialize next time
reflection Speaking of Vue cache , We must first choose the caching scheme provided by the official keep-alive Built in components to achieve .
keep-alive Components provide us with the ability to cache components , You can completely save the state of the current component , This helped us a lot
But in the actual business scenario , We often cache pages on demand , It's like App Develop that , Each page is a separate page instance , because Vue Router The limitation of , Each page has a fixed path, So every time you visit this path Will hit the same component instance
At this time, some friends may say
EH , No, you can use
activatedTo update or process the page ?
you 're right , It can be like this , however , Some operations are mounted It needs to be done inside , Some need to be put activated Update inside , The code has to deal with many operations to enter the page , It's very troublesome .
At this point, there are two directions of thinking :
Clear instances of cached pages when necessary
Every time push On the page , Ensure that the current page is a new instance object , and App Same page stack
The second solution can physically solve the problems in the requirements , But there are many things that need to be changed , such as Vue Router When the middle road switches , Whether to use dynamic generation path , Ensure that the current page instance is not unique , And we should also do our own page stack management , Be similar to iOS Medium UINavigationController , In order to clean up the cached page instances in the stack in time
Because the changes are big , And it requires a lot of testing , So I finally chose Scheme 1 Explore and try in the direction of .
Try 1. Manual operation keep-alive Component's cache Array// Vue 2 keep-alive Some source code fragments const { cache, keys } = this;const key: ?string = vnode.key == null ? // same constructor may get registered as different local components // so cid alone is not enough (#3269) componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : "") : vnode.key;if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key);} else { // delay setting the cache until update this.vnodeToCache = vnode; this.keyToCache = key;} adopt Route guard Delete under certain circumstances cache Page instances in the array , meanwhile destory The current instance
removeKeepAliveCacheForVueInstance(vueInstance) { let key = vueInstance.$vnode.key ?? vueInstance.$vnode.componentOptions.Ctor.cid + (vueInstance.$vnode.componentOptions.tag ? `::${vueInstance.$vnode.componentOptions.tag}` : ""); let cache = vueInstance.$vnode.parent.componentInstance.cache; let keys = vueInstance.$vnode.parent.componentInstance.keys; if (cache[key]) { vueInstance.$destroy(); delete cache[key]; let index = keys.indexOf(key); if (index > -1) { keys.splice(index, 1); } }} This scheme is cumbersome , But because it is a direct operation cache Array , There may be some unexpected leakage problems or operation problems , Although I didn't find it when I tried it myself ..
stay Vue 3 I also try to find the corresponding cache Array , I found it , however Vue 3 Source code for cache The operation permission of array is limited to the development environment
// Vue 3 KeepAlive Component fragment if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { ;(instance as any).__v_cache = cache} After deploying the production environment, you can't pass instance.__v_cache To get cache Array , So this plan to Vue 3 There is no way to proceed .
So , There is a second attempt
2. exclude Dafa is good Before contact with keep-alive All attention is focused on include This attribute is above , Actually exclude Attributes are equally important , And the effect is the same as our direct deletion cache Arrays are similar .
// Vue 3 KeepAlive Component fragment if ( (include && (!name || !matches(include, name))) || (exclude && name && matches(exclude, name)) ) { current = vnode return rawVNode } If exclude It's worth it , Then return the current new instance instead of cache Get in there . and exclude Priority is higher than include Of .
Take advantage of this , We can do this by manipulating exclude The content in , To achieve the effect of controlling the cached page .
and exclude stay Vue 3 The control in is more convenient , Just define a global exclude Reactive variables can be operated anywhere , The specific way of clearing depends on the business process
export const excludes = ref<string[]>([]);// When it needs to be deleted export function removeKeepAliveCache(name: string) { excludes.value.push(name);}// When the cache needs to be restored export function resetKeepAliveCache(name: string) { excludes.value = excludes.value.filter((item) => item !== name);}DemoHere's a little demo Demonstrate the cache clearing effect :
https://ztstory.github.io/vue-composition-demo/#/
technological process :
Index And Input Cache pages for Input Back to Index Clear when Input cache , Re enter Input Page activation cache Demo Source code address :https://github.com/ZTStory/vue-composition-demo
Here is a detailed explanation of Vue Timely cleaning keepalive This is the end of the article on caching solutions , More about Vue clear keepalive Please search the previous articles of SDN or continue to browse the related articles below. I hope you can support SDN more in the future !
边栏推荐
- C - Divisors of the Divisors of An Integer Gym - 102040C
- 不相交集
- R language ggplot2 visual density map: Visual density map by group and custom configuration geom_ The alpha parameter in the density function sets the image transparency (to prevent multiple density c
- R语言ggplot2可视化条形图:通过双色渐变配色颜色主题可视化条形图、为每个条形添加标签文本(geom_text函数)
- The IPO of Ruineng industry was terminated: the annual revenue was 447million and it was planned to raise 376million
- Niuke: intercepting missiles
- How can non-technical departments participate in Devops?
- Online electronic component purchasing Mall: break the problem of information asymmetry in the purchasing process, and enable enterprises to effectively coordinate management
- R语言dplyr包select函数、group_by函数、mutate函数、cumsum函数计算dataframe分组数据中指定数值变量的累加值、并生成累加数据列
- 魅族新任董事长沈子瑜:创始人黄章先生将作为魅族科技产品战略顾问
猜你喜欢

循环不变式

申请代码签名证书时如何选择合适的证书品牌?

Share 20 strange JS expressions and see how many correct answers you can get

LeetCode_ 2 (add two numbers)

世界环境日 | 周大福用心服务推动减碳环保
![Which Internet companies are worth going to in Shenzhen for software testers [Special Edition for software testers]](/img/c2/a5f5fe17a6bd1f6f9df828ddd224d6.png)
Which Internet companies are worth going to in Shenzhen for software testers [Special Edition for software testers]

Why do mechanical engineers I know complain about low wages?

家用电器行业商业供应链协同平台解决方案:供应链系统管理精益化,助推企业智造升级

Kunlun Taike rushes to the scientific innovation board: the annual revenue is 130million, and it plans to raise 500million. CETC Taiji holds 40% of the shares

Zhizhen new energy rushes to the scientific innovation board: the annual revenue is 220million, and SAIC venture capital is the shareholder
随机推荐
What category does the Internet of things application technology major belong to
Why do mechanical engineers I know complain about low wages?
C - Divisors of the Divisors of An Integer Gym - 102040C
Introduction, installation, introduction and detailed introduction to postman!
MySQL user-defined function ID number to age (supports 15 / 18 digit ID card)
Chow Tai Fook fulfills the "centenary commitment" and sincerely serves to promote green environmental protection
TiFlash 面向编译器的自动向量化加速
The IPO of Ruineng industry was terminated: the annual revenue was 447million and it was planned to raise 376million
openGauss数据库源码解析系列文章—— 密态等值查询技术详解(下)
分享 12 个最常用的正则表达式,能解决你大部分问题
R language ggplot2 visual bar graph: visualize the bar graph through the two-color gradient color theme, and add label text for each bar (geom_text function)
R语言使用nnet包的multinom函数构建无序多分类logistic回归模型、使用coef函数获取模型中每个变量(自变量改变一个单位)对应的对数优势比(log odds ratio)
C语言中限定符的作用
R language uses boxplot function in native package (basic import package, graphics) to visualize box plot
动态规划
freesurfer运行完recon-all怎么快速查看有没有报错?——核心命令tail重定向
Time to calculate cron expression based on cronsequencegenerator
非技术部门,如何参与 DevOps?
Don't be unconvinced. Mobile phone function upgrade is strong
Countermeasures of enterprise supply chain management system in UCA Era