keep-alive理解与总结


谈谈keep-alive的理解

1.什么是keep-alive?

keep-alive就是Vue自带的一个组件,它可以用来缓存组件,提高页面性能。

注意这个 要求被切换到的组件都有自己的名字,不论是通过组件的 name 选项还是局部/全局注册。

2.使用场景有哪些?

例如一个商品的详情页组件,用户不小心返回了,再次进入就得重新网络请求。

那么我们就可以用keep-alive来进行缓存,在activated上进行id判断。如果id相同,那么直接使用缓存就行;如果id不同,那么才需要发送网络请求;

逻辑如下:

data:{
    content:{},
    id:0
}
created(){

},

activated(){
    if(this.$route.query.id !== this.id){
        this.id = this.$route.query.id;
        this.getData();
    }
},

methods:{
    getData(){
                axios({
            url:'http://xxx',
            params:{
                id:this.id
            }
        }).then(res){
            this.content = res.content;
        }
    }
}

3. keep-alive的使用方法

3.1 组件属性缓存

include和exclude指定是否缓存某些组件

(1) include属性

include 包含的意思。值为字符串或正则表达式或数组。只有组件的名称与include的值相同的才会被缓存,即指定哪些被缓存,可以指定多个被缓存。这里以字符串为例,指定多个组件缓存,语法是用逗号隔开。如下:

// 指定home组件和about组件被缓存

<keep-alive include="home,about" >
    <router-view></router-view>
</keep-alive>

(2) exclude属性

exclude相当于include的反义词,就是除了的意思,指定哪些组件不被缓存,用法和include类似,如下:

// 除了home组件和about组件别的都缓存,本例中就是只缓存detail组件

<keep-alive exclude="home,about" >
    <router-view></router-view>
</keep-alive>

注:
keep-alive除了include和exclude属性之外,还有一个属性就是max属性,这个max一般情况用的不是太多,主要目的就是控制一下被缓存的组件的个数,后缓存的就会把先缓存的给挤掉线了,也是相当于缓存优化的一中策略了。毕竟适当缓存提高用户体验,缓存过渡,电脑变卡。

3.2 路由规则 meta

// routes 配置
export default [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      keepAlive: true // 需要被缓存
    }
  }, {
    path: '/profile',
    name: 'profile',
    component: Profile,
    meta: {
      keepAlive: false // 不需要被缓存
    }
  }
]
<keep-alive>
    <router-view v-if="$route.meta.keepAlive">
        <!-- 这里是会被缓存的视图组件,比如 Home! -->
    </router-view>
</keep-alive>

<router-view v-if="!$route.meta.keepAlive">
    <!-- 这里是不会被缓存的视图组件,比如 Profile! -->
</router-view>

文章作者: iamfugui
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iamfugui !
评论
  目录