1. 程式人生 > 其它 >vue3中keep-alive及include/exclude的使用

vue3中keep-alive及include/exclude的使用

技術標籤:Vue

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>
<!-- 使用路由快取 -->