vue.js 내장 구성 요소의 연결 유지 구성 요소 사용에 대한 자세한 예
keep-alive는 Vue.js에 내장된 구성 요소입니다. 이번 글에서는 주로 vue.js에 내장된 컴포넌트인 keep-alive 컴포넌트의 사용법을 소개합니다. 필요한 친구들이 참고하면 됩니다.
keep-alive는 Vue.js에 내장된 컴포넌트입니다.
예를 들어
<keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view>
버튼을 클릭하면 두 입력이 전환되지만 이때 두 입력 상자의 상태는 캐시되며 입력 태그의 내용은 캐시되지 않습니다. 구성 요소를 전환할 때 사라짐으로 인해 변경됩니다.
* 포함 - 문자열 또는 정규식. 일치하는 구성 요소만 캐시됩니다.
* 제외 - 문자열 또는 정규식. 일치하는 구성 요소는 캐시되지 않습니다.
<keep-alive include="a"> <component></component> </keep-alive>
이름이 a
<keep-alive exclude="a"> <component></component> </keep-alive>
이름이 a인 컴포넌트를 제외하고 다른 모든 컴포넌트는 캐시됩니다.
Life Cycle Hook
Life Hook Keep -alive는 활성화 및 비활성화라는 두 가지 구명 후크를 제공합니다.
Keep-alive는 구성 요소를 메모리에 저장하고 이를 파괴하거나 다시 생성하지 않으므로 구성 요소의 생성 및 기타 메서드를 다시 호출하지 않기 때문에 활성화 및 비활성화의 두 가지 생명 고리를 사용해야 합니다. 현재 구성 요소가 활성 상태인지 확인합니다.
keep-alive 구성요소 구현에 대해 자세히 알아보세요
vue--keep-alive 구성요소 소스 코드를 보고 다음 정보를 얻으세요
생성된 후크는 캐시 개체를 생성합니다. vnode 노드를 저장하는 캐시 컨테이너.
props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created () { // 创建缓存对象 this.cache = Object.create(null) // 创建一个key别名数组(组件name) this.keys = [] },
destroyed 후크는 구성 요소가 삭제될 때 캐시의 모든 구성 요소 인스턴스를 지웁니다.
destroyed () { /* 遍历销毁所有缓存的组件实例*/ for (const key in this.cache) { pruneCacheEntry(this.cache, key, this.keys) } },
:::demo
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)) }) },
:::
Vue 소스 코드를 보면 keep-alive가 기본적으로 include,clude,max 3가지 속성을 전달하는 것을 볼 수 있습니다. , 최대 캐시 길이
소스 코드와 결합하여 구성 가능한 캐시로 라우터 보기를 구현할 수 있습니다
<!--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 根据项目是否需要缓存的页面数量多少来决定-->
keepAliveConf.js를 만들고 일치해야 하는 구성 요소 이름을 배치합니다
// 路由组件命名集合 var arr = ['component1', 'component2']; export default {value: routeList.join()};
캐시를 재설정하는 전역 메소드 구성
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); } } }, } })
적절한 시점에 this.resetKeepAive(name)를 호출하여 구성 요소 인스턴스를 파괴하기 위해 연결 유지를 트리거합니다.
Vue.js; DOM 노드를 VNode 노드로 추상화하고 -alive 구성 요소의 캐시도 DOM 구조를 직접 저장하는 대신 VNode 노드를 기반으로 합니다. 캐시 개체의 조건을 충족하는 구성 요소를 캐시한 다음 캐시 개체에서 vnode 노드를 꺼내 다시 렌더링해야 할 때 렌더링합니다.
위 내용은 vue.js 내장 구성 요소의 연결 유지 구성 요소 사용에 대한 자세한 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











HTML 템플릿의 버튼을 메소드에 바인딩하여 VUE 버튼에 함수를 추가 할 수 있습니다. 메소드를 정의하고 VUE 인스턴스에서 기능 로직을 작성하십시오.

vue.js에서 JS 파일을 참조하는 세 가지 방법이 있습니다. & lt; script & gt; 꼬리표;; mounted () 라이프 사이클 후크를 사용한 동적 가져 오기; Vuex State Management Library를 통해 수입.

vue.js에서 bootstrap 사용은 5 단계로 나뉩니다 : Bootstrap 설치. main.js.의 부트 스트랩 가져 오기 부트 스트랩 구성 요소를 템플릿에서 직접 사용하십시오. 선택 사항 : 사용자 정의 스타일. 선택 사항 : 플러그인을 사용하십시오.

vue.js의 시계 옵션을 사용하면 개발자가 특정 데이터의 변경 사항을들을 수 있습니다. 데이터가 변경되면 콜백 기능을 트리거하여 업데이트보기 또는 기타 작업을 수행합니다. 구성 옵션에는 즉시 콜백을 실행할지 여부와 DEEP를 지정하는 즉시 포함되며, 이는 객체 또는 어레이에 대한 변경 사항을 재귀 적으로 듣는 지 여부를 지정합니다.

vue.js는 이전 페이지로 돌아갈 수있는 네 가지 방법이 있습니다. $ router.go (-1) $ router.back () 사용 & lt; router-link to = & quot;/quot; Component Window.history.back () 및 메소드 선택은 장면에 따라 다릅니다.

CSS 애니메이션 또는 타사 라이브러리를 사용하여 VUE에서 Marquee/Text Scrolling Effects를 구현하십시오. 이 기사는 CSS 애니메이션 사용 방법을 소개합니다. & lt; div & gt; CSS 애니메이션을 정의하고 오버플로를 설정하십시오 : 숨겨진, 너비 및 애니메이션. 키 프레임을 정의하고 변환을 설정하십시오 : Translatex () 애니메이션의 시작과 끝에서. 지속 시간, 스크롤 속도 및 방향과 같은 애니메이션 속성을 조정하십시오.

Vue DevTools를 사용하여 브라우저 콘솔에서 vue 탭을 보면 VUE 버전을 쿼리 할 수 있습니다. npm을 사용하여 "npm list -g vue"명령을 실행하십시오. package.json 파일의 "종속성"객체에서 vue 항목을 찾으십시오. Vue Cli 프로젝트의 경우 "vue -version"명령을 실행하십시오. & lt; script & gt에서 버전 정보를 확인하십시오. vue 파일을 나타내는 html 파일의 태그.

vue.js가 트래버스 어레이 및 객체에 대한 세 가지 일반적인 방법이 있습니다. V- 결합 지시문은 V-FOR와 함께 사용하여 각 요소의 속성 값을 동적으로 설정할 수 있습니다. .MAP 메소드는 배열 요소를 새 배열로 변환 할 수 있습니다.
