赞
踩
<keep-alive > 是vue内置的一个组件,可用于缓存动态组件 ,使包裹的动态组件在切换时 保存状态,避免重新渲染
可以缓存组件,也可以缓存路由
- <template>
- <div>
-
- <button @click="switchPage">切换页面</button>
-
- <keep-alive >
-
- <component :is="curentComponent"></component>
-
- </keep-alive>
-
- </div>
- </template>
-
- <script>
-
- import ComponentA from '@/components/ComponentA.vue'
-
- import ComponentB from '@/components/ComponentB.vue'
-
- import ComponentC from '@/components/ComponentC.vue'
-
- export default {
-
- components: {
-
- ComponentA,
-
- ComponentB,
-
- ComponentC
-
- },
-
- data () {
-
- return {
-
- user: {},
-
- curentComponent: 'ComponentA'
-
- }
-
- },
-
- methods: {
-
- switchPage () {
-
- this.curentComponent = this.curentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'
-
- },
-
- }
-
- }
-
- </script>
keep-alive 缓存的组件会有两个钩子函数:activated 和 deactivated
第一次进入被缓存的组件A 会触发beforeCreate ==>created ==>beforeMount ==>mounted ==>activated
离开被缓存的A组件 进入被缓存的B组件,会触发A组件的 deactivated ,则第一次进入被缓存的B组件 会触发beforeCreate ==>created ==>beforeMount ==>A组件的deactivated ==>mounted ==>activated
第二次再进这个被缓存的组件A 只触发activated ,不会再触发beforeCreate, created , beforeMount, mounted
keep-alive 可配置 include 属性,需要保证组件的名称(name)与 include 的值相同的才会被缓存
<div>
<button @click="switchPage">切换页面</button>
<keep-alive include="ComponentBpage,ComponentCpage">
<component :is="curentComponent"></component>
</keep-alive>
</div>
exclude 排除 指定哪些组件不被缓存,优先级大于 include,同include ,需要保证组件的名称(name)与 exclude 的值相同
<div>
<button @click="switchPage">切换页面</button>
<!-- <keep-alive include="ComponentBpage,ComponentCpage"> -->
<keep-alive exclude="ComponentBpage">
<component :is="curentComponent"></component>
</keep-alive>
</div>
被缓存后的组件 数据获取方式:
在activated 中获取,因为进入缓存组件 不会触发 created 和 mounted钩子函数,会触发activated 钩子函数
在 beforeRouteEnter 钩子函数中,在路由进入之前先获取数据。每次组件渲染或者每次进入路由的时候,都会执行 beforeRouteEnter
缓存路由:
include 也可以使用数组,使用 v-bind
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。