1.动态组件
js代码:
// 定义组件
const AAA = {
template: '#aaa'
};
const BBB = {
template: '#bbb'
};
const CCC = {
template: '#ccc'
};
const app = new Vue({
el: '#app',
data: {
a: 'aaa', // a变量的值和注册组件的属性名相对应
},
// 注册组件
components: {
'aaa': AAA,
'bbb': BBB,
'ccc': CCC,
}
});
组件:
<template id="aaa">
<h3>这是aaa组件</h3>
</template>
<template id="bbb">
<h3>这是bbb组件</h3>
</template>
<template id="ccc">
<h3>这是ccc组件</h3>
</template>
html代码:
<div id="app">
<button @click='a = "aaa"'>组件A</button>
<button @click='a = "bbb"'>组件B</button>
<button @click='a = "ccc"'>组件C</button>
<component :is='a'></component>
<!-- vue中固有的component标签,vue中 'is' 关键字用来动态切换组件 -->
<!--由于这里a是变量,所以is前加v-bind动态绑定-->
</div>
页面效果
点击每个按钮会显示相对应的组件内容。
BUT:动态组件默认情况下切换时都是先销毁原来的组件,再创建新的组件!!!
2.动态组件间切换时的缓存
假如需要保留上一次的结果,避免组件的重新渲染,可以使用<keep-alive></keep-alive>
包裹component
。实例:手机中使用完某款软件,你按了一下HOME按键,此时应用并没有完全关闭。
例:
<keep-alive>
<component :is='a'></component>
</keep-alive>
但是此时又有问题了,之前是全部都销毁了,现在是全部都缓存了,能不能只缓存需要的呢?当然可以:
定义组件时添加name选项,keep-alive 添加include属性,值为name选项,需要缓存的写进去
keep-alive 会伴随有两个生命周期钩子函数 activated deactivated
activated () { // 激活 后台应用程序正在使用}
deactivated () { // 隐藏 在后台应用中,但不是关闭了的(按了home键的)}
例如我们只保留aaa和bbb两个组件间的内容:
<keep-alive include='aaa,bbb'>
<component :is='a'></component>
</keep-alive>
在每个组件按钮后添加一个文本框,观察切换组件后是否文本框的内容还存在:
<template id="aaa">
<h3>这是aaa组件<input type="text"></h3>
</template>
<template id="bbb">
<h3>这是bbb组件<input type="text"></h3>
</template>
<template id="ccc">
<h3>这是ccc组件<input type="text"></h3>
</template>