


Detailed examples of the use of keep-alive components of vue.js built-in components
keep-alive is a built-in component of Vue.js. This article mainly introduces the use of the keep-alive component of the built-in component of vue.js. Friends in need can refer to
keep-alive is a built-in component of Vue.js.
Give a chestnut
<keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view>
* include - string or regular expression. Only matching components will be cached.* exclude - string or regular expression. Any matching components will not be cached.
<keep-alive include="a"> <component></component> </keep-alive>
<keep-alive exclude="a"> <component></component> </keep-alive>
Life cycle hook
Life hook keep-alive provides two life hooks , respectively activated and deactivated. Because keep-alive will save the component in the memory and will not destroy or recreate it, the created and other methods of the component will not be re-called. You need to use the two life hooks of activated and deactivated to know the current situation. Whether the component is active. In-depth implementation of keep-alive component
props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created () { // 创建缓存对象 this.cache = Object.create(null) // 创建一个key别名数组(组件name) this.keys = [] },
destroyed () { /* 遍历销毁所有缓存的组件实例*/ for (const key in this.cache) { pruneCacheEntry(this.cache, key, this.keys) } },
render () { /* 获取插槽 */ const slot = this.$slots.default /* 根据插槽获取第一个组件组件 */ const vnode: VNode = getFirstComponentChild(slot) const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions if (componentOptions) { // 获取组件的名称(是否设置了组件名称name,没有则返回组件标签名称) const name: ?string = getComponentName(componentOptions) // 解构对象赋值常量 const { include, exclude } = this if ( /* name不在inlcude中或者在exlude中则直接返回vnode */ // not included (include && (!name || !matches(include, name))) || // excluded (exclude && name && matches(exclude, name)) ) { return vnode } 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 { cache[key] = vnode keys.push(key) // 判断是否设置了最大缓存实例数量,超过则删除最老的数据, if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode) } } // 给vnode打上缓存标记 vnode.data.keepAlive = true } return vnode || (slot && slot[0]) } // 销毁实例 function pruneCacheEntry ( cache: VNodeCache, key: string, keys: Array<string>, current?: VNode ) { const cached = cache[key] if (cached && (!current || cached.tag !== current.tag)) { cached.componentInstance.$destroy() } cache[key] = null remove(keys, key) } // 缓存 function pruneCache (keepAliveInstance: any, filter: Function) { const { cache, keys, _vnode } = keepAliveInstance for (const key in cache) { const cachedNode: ?VNode = cache[key] if (cachedNode) { const name: ?string = getComponentName(cachedNode.componentOptions) // 组件name 不符合filler条件, 销毁实例,移除cahe if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode) } } } } // 筛选过滤函数 function matches (pattern: string | RegExp | Array<string>, name: string): boolean { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } // 检测 include 和 exclude 数据的变化,实时写入读取缓存或者删除 mounted () { this.$watch('include', val => { pruneCache(this, name => matches(val, name)) }) this.$watch('exclude', val => { pruneCache(this, name => !matches(val, name)) }) },
:::
By looking at the Vue source code, we can see that keep-alive passes 3 attributes by default, include, exclude, max, max the maximum cacheable length
Combined with the source code, we can implement a router with configurable cache -view
<!--exclude - 字符串或正则表达式。任何匹配的组件都不会被缓存。--> <!--TODO 匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称--> <keep-alive :exclude="keepAliveConf.value"> <router-view class="child-view" :key="$route.fullPath"></router-view> </keep-alive> <!-- 或者 --> <keep-alive :include="keepAliveConf.value"> <router-view class="child-view" :key="$route.fullPath"></router-view> </keep-alive> <!-- 具体使用 include 还是exclude 根据项目是否需要缓存的页面数量多少来决定-->
Create a keepAliveConf.js and place the component name that needs to match
// 路由组件命名集合 var arr = ['component1', 'component2']; export default {value: routeList.join()};
Configure the global method of resetting the cache
import keepAliveConf from 'keepAliveConf.js' Vue.mixin({ methods: { // 传入需要重置的组件名字 resetKeepAive(name) { const conf = keepAliveConf.value; let arr = keepAliveConf.value.split(','); if (name && typeof name === 'string') { let i = arr.indexOf(name); if (i > -1) { arr.splice(i, 1); keepAliveConf.value = arr.join(); setTimeout(() => { keepAliveConf.value = conf }, 500); } } }, } })
Call this.resetKeepAive(name) at the appropriate time to trigger keep-alive to destroy the component instance;
Vue.js internally abstracts DOM nodes into VNode nodes. The cache of the keep-alive component is also based on VNode nodes instead of directly storing the DOM structure. It caches the components that meet the conditions in the cache object, and then takes the vnode node out of the cache object and renders it when it needs to be re-rendered.
The above is the detailed content of Detailed examples of the use of keep-alive components of vue.js built-in components. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.
