X
XiaoSong
V1
2023/02/27阅读:53主题:默认主题
Vue3的动态组件与keepalive组件
动态组件
<component>
常用于组件间来回切换的场景,比如说Tab。具体使用方式如下:<component :is='组件名/组件对象'>
<template>
<div>
<button
v-for="(value, key) in tabs"
:key="key"
@click="currentTab = key"
>
{{ key }}
</button>
<component :is="tabs[currentTab]"></component>
</div>
</template>
import Home from '../components/sportComp/home.vue'
import User from '../components/sportComp/user.vue'
import Find from '../components/sportComp/find.vue'
import {ref} from 'vue'
const currentTab = ref('Home')
const tabs = { Home, User, Find }
以上代码中,把引入的组将放入tabs
对象中, 默认显示的组件currentTab
为Home
。循环tabs
对象创建3个按钮,被点击时把currentTab
=currentTab
, <component>
中 :is=当前组件
。
NOTE: 当切换组件之后之前的组件会被销毁。看如下例子。我们在每个组件中加上输入框,当我输入内容后,切换到别的组件在切换回来后输入框内容会消失。

切换到user组件之后在切换到find组件,输入框内容消失。

KeepAlive
使用
<KeepAlive>
可以把切换后被销毁的组件缓存起来。我们把以上代码使用<KeepAlive>
进行包裹。当再次进行切换的时候之前文本框内容保存着。
<KeepAlive>
<component :is="tabs[currentTab]"></component>
</KeepAlive>
作者介绍
X
XiaoSong
V1