- 动态组件, v-if,v-show的区别
v-if: 动态的向DOM树内添加或者删除DOM元素,切换一次就需要重新渲染一次组件;
v-if + v-once: 把组件缓存起来,只渲染元素和组件一次,避免了来回创建销毁耗费的性能,支持 <template>
元素;
v-show: 通过设置DOM元素的display样式属性控制显隐,是一开始就渲染的所有组件 , 之后只是样式的显示与隐藏 ,不支持 <template>
元素
动态组件: 配合使用时,显示的时候 html上就有这个标签, 隐藏的时候,就不显示在html上, 但是不会再次渲染组件
- 动态组件的使用
<button
@click="change"
style="position: absolute; top: 48px;z-index: 3;right: 120px"
>
{{ index ? "2D" : "3D" }}地图
</button>
<!--动态组件,实现地图切换-->
<keep-alive>
<component :is="componentName" :mapReady="mapReady"></component>
</keep-alive>
import Map3D from "./map3D/map3D";
import MapD2 from "./map2D/MapD2";
export default {
components: {Map3D, MapD2},
data() {
return {
mapReady: true,
index: 0,
arr: [MapD2, Map3D],
};
},
computed: {
componentName() {
return this.arr[this.index];
}
},
methods: {
change() {
this.index = (++this.index) % 2;
}
}
};