Vue中基于组件的方式来开发,需要控制组件的切换效果(显示和隐藏)
最常见的效果就是tabs切换。比如你们在进行登录。可以账户密码登录,也可以是电话短信验证登录
Vue中提供了component标签用于动态组件渲染
-
<template> <div> <div> <button @click="current='ChildA'">显示A</button> <button @click="current='ChildB'">显示B</button> </div> <component :is="current"></component> <!-- <ChildA></ChildA> --> <!-- <ChildB></ChildB> --> </div> </template> <script> import ChildA from "./ChildA.vue" import ChildB from "./ChildB.vue" export default { data(){ return{ current:"ChildB" } }, components:{ ChildA,ChildB } } </script> <style> </style>
component这个标签不会引入任何的节点代码。默认必须要有is属性
is属性的值等于子组件名字,默认加载这个组件。
组件销毁
使用动态组件来进行组件切换的时候,消失的组件默认会被销毁处理。
-
<template> <div> <h2>ChildB</h2> </div> </template> <script> export default { destroyed(){ console.log("ChildB销毁了"); } } </script> <style> </style>
只要切换,destroyed就会执行,说明被销毁。
keepalive组件
在动态组件开发过程中,我们切换组件,默认会被销毁。在表单输入的组件里面,这种用户体验就比较差。想要切换过后组件不会被销毁。填写的数据还在。
Vue提供了一个keepalive组件,可以用于缓存组件。
-
<keep-alive> <component :is="current"></component> //ChildA ChildB </keep-alive>
一旦被keep-alive包裹的组件,默认就会被缓存起来。切换后不会被销毁
keep-alive
:这个组件有一些常用的属性介绍给大家:
include:值可以是字符串也可以正则表达式,include代表白名单,哪些需要被缓存,写在这个属性里面。
exclude:值可以是字符串也可以正则表达式,exclude代表黑名单,一旦设置组件的名字,代表默认不被缓存
max:代表当前缓存的最大数量,max=”10”,默认最多只能缓存10个组件,LRU策略,如果有第十一个组件来了,将之前10个最长时间不使用组件销毁了。将最新的第十一个存放进去
-
<template> <div> <div> <button @click="current = 'ChildA'">显示A</button> <button @click="current = 'ChildB'">显示B</button> </div> <keep-alive include="ChildA" exclude="ChildB" max="10"> <component :is="current"></component> </keep-alive> </div> </template> <script> import ChildA from "./ChildA.vue"; import ChildB from "./ChildB.vue"; export default { data() { return { current: "ChildB", }; }, components: { ChildA, ChildB, }, }; </script> <style> </style>
activated
:keep-alive激活这个组件的时候,默认执行,切换显示他的时候
deactivated
:keep-alive在组件中停用的时候。默认执行,切换隐藏他的时候
这个两个生命周期钩子函数,只能使用了keep-alive包裹的组件中用
-
<template> <div> <h2>ChildA</h2> <input type="text"> <ul> <li v-for="item in users" :key="item">{{item}}</li> </ul> </div> </template> <script> export default { data(){ return{ users:["小王","小张","小李"] } }, created(){ //发送异步请求 setTimeout(() => { this.users = ["小飞飞","小李子","张应明"] }, 1000); console.log("ChildA-created"); }, destroyed(){ console.log("ChildA销毁了"); }, activated(){ console.log("组件被激活显示"); }, deactivated(){ console.log("组件被停用"); } } </script> <style> </style>