动态组件
让多个组件使用同一个<component></component>挂载点,并动态切换组件。
其具体实现是在一个多标签的界面中使用 is 属性来动态切换不同的组件,如:
<!--在component中使用is属性绑定组件--> <component v-bind:is="currentTabComponent"></component>
动态组件具体实现如下:
<template> <div> <button @click="change">动态组件切换</button> <!--动态组件--> <component :is="currentComponent"></component> </div> </template> <script> export default { // 引入组件 components: { one: { template: "<div>组件1</div>" }, two: { template: "<div>组件2</div>" }, three: { template: "<div>组件3</div>" }, }, data: { index: 0, arr: ["one", "two", "three"], // 初始组件信息 currentComponent: "one", }, methods: { // 动态切换组件 change() { //取余 this.index = ++this.index % 3; //切换组件 this.currentComponent = this.arr[this.index]; }, }, } </script>
条件判断组件动态加载
除了通过动态组件的形式实现组件的动态切换,也可以通过多条件判断的方式实现组件的切换,具体实现如下:
<!-- 多个条件判断的子组件 --> <template> <div> <button @click="change">动态组件切换</button> <!-- 多个条件判断的子组件 --> <one v-if="currentComponent == 'one'"></one> <two v-else-if="currentComponent == 'two'"></two> <threev-else></three> </div> </template>
动态组件缓存
动态组件在组件之间切换的时候,会重复渲染组件的内容,但对于有些想保持组件状态的场景来说,会出现反复重渲染导致的性能问题。
为了解决切换时重新创建组件的问题,我们可以用一个 <keep-alive> 元素将动态组件包裹起来,实现页面组件的缓存效果,具体实现如下:
<template> <div> <button @click="change">动态组件切换</button> <!-- 失活的组件将会被缓存!--> <keep-alive> <component :is="currentComponent"></component> </keep-alive> </div> </template>
<keep-alive> 元素会缓存不活动的组件实例,而不是销毁它们。
<keep-alive> 元素在多条件判断的子组件的应用如下:
<template> <div> <button @click="change">动态组件切换</button> <!-- 多个条件性的子元素 --> <keep-alive> <one v-if="currentComponent == 'one'"></one> <two v-else-if="currentComponent == 'two'"></two> <three v-else></three> </keep-alive> </div> </template>
注意:
- <keep-alive> 是用在其一个直属的子组件被应用的情形;
- 如果在<keep-alive>中有 v-for ,则不会工作
- 如果有多个条件性的子元素,<keep-alive> 要求同时只有一个子元素被渲染;