vue3中keep-alive及include/exclude的使用
1、首先准备前期环境,路由配置及界面配置const addRouters: Array<RouteRecordRaw> = [{//路由path:'/',name:'home',component:() => import('@/views/home/home.vue'),children:[{path:'/',redirect:'/A'},{path:'/A',name:'A'
·
1、首先准备前期环境,路由配置及界面配置
const addRouters: Array<RouteRecordRaw> = [{//路由
path:'/',
name:'home',
component:() => import('@/views/home/home.vue'),
children:[{
path:'/',
redirect:'/A'
},{
path:'/A',
name:'A',
component:() => import('@/views/A/A.vue')
},{
path:'/B',
name:'B',
component:() => import('@/views/B/B.vue')
},{
path:'/C',
name:'C',
component:() => import('@/views/C/C.vue')
},{
path:'/D',
name:'D',
component:() => import('@/views/D/D.vue')
}]
}]
<template>
<div class="home">
<div class="router-btn">
<el-button type="primary" @click="routerTo('A')" size="small">路由A</el-button>
<el-button type="success" @click="routerTo('B')" size="small">路由B</el-button>
<el-button type="warning" @click="routerTo('C')" size="small">路由C</el-button>
<el-button type="danger" @click="routerTo('D')" size="small">路由D</el-button>
</div>
<div class="router-view">
<router-view class="box"></router-view>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { useRouter } from 'vue-router';
export default defineComponent({
name:'home',
setup () {
const router = useRouter();//使用路由
const routerTo = (path:string) => {
router.push({name:path});
}
return {
routerTo
}
}
})
</script>
<style scoped lang='scss'>
.home{
display: flex;
flex-flow: column;
.router-btn{
padding: 10px;
box-sizing: border-box;
}
.router-view{
border-top: 1px solid #d8d8d8;
flex:1;
}
}
</style>
效果图:
2、接下来我们根据上面的前期条件,加入keep-alive,实现路由缓存
//home.vue中
<!-- 使用路由缓存 -->
<router-view class="box" v-slot={Component}>
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
<!-- 使用路由缓存 -->
<template>
<div>
路由B
<p>{{num}}</p>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
name:'B',
setup () {
const num = ref<number>(0);
setInterval(() => {
num.value++;
},1000);
return {
num
}
}
})
</script>
<style scoped>
</style>
3、经过上面改版,现在切换路由已经有了缓存
4、使用exclude,除了组件B,其余组件缓存,include就是包含的组件需要缓存
<!-- 使用路由缓存 -->
<router-view class="box" v-slot={Component}>
<keep-alive :exclude="['B']">
<component :is="Component" />
</keep-alive>
</router-view>
<!-- 使用路由缓存 -->
更多推荐
已为社区贡献10条内容
所有评论(0)