2-15-动态组件

什么是动态组件

动态组件指的是动态切换组件的显示与隐藏。

如何实现动态组件渲染

vue提供一个组件,专门用来实现动态组件的渲染。示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
data() {

return { comName: 'Left' }

}

<component :is='comName'></component>

<button @click="comName = 'Left'">显示Left组件</button>

<button @click="comName = 'Right'">显示Right组件</button>

实用场景


点击页签切换页面。

使用keep-alive保证组件不被销毁

默认的动态组件,一旦切换成其他组件,之前的组件就会被销毁。

这个可以通过监听生命周期中的destroyed和created来得知:

1
2
3
4
5
6
7
8
9
10
11
created(){

console.log("Left组件被创建");

}

destroyed() {

console.log("Right组件被创建");

}

这时使用keep-alive就可以保证动态组件不会被销毁

1
2
3
4
5
<keep-alive>

<component :is="comName"></component>

</keep-alive>

加上之后,就会发现所有显示过的组件都会被打上inactivated的标签,而不是被销毁掉

当组件被缓存时,会自动触发组件的deactivated生命周期函数

当组件被激活时,会自动触发组件的activated生命周期函数

1
2
3
4
5
6
7
8
9
10
11
deactivated() {

console.log("组件被缓存");

}

activated() {

console.log("组件被激活");

}
  1. keep-alive中的include属性

include属性用来指定:只有与名称匹配的组件才会被缓存。多个组件名之间使用英文逗号分隔:

1
2
3
4
5
<keep-alive include="MyLeft, MyRight">

<component :is="comName">

</keep-alive>

另外还有exclude,用于指定哪些组件不能被缓存,exclude和include不能同时使用。

  1. 声明name
1
2
3
4
export default {
name: "MyRight"

}

当声明name为MyRight时,前面include中指定的组件名称就要跟name一致。

参考:

https://www.bilibili.com/video/BV1zq4y1p7ga?p=147&spm_id_from=pageDriver


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!