1、动态组件( component ):根据 is 里面数据的变化自动加载不同的组件
<template> <div class="main-box"> <div class="box"> <component :is="type"></component> <el-button type="primary" @click="handleBtnClick">change</el-button> </div> </div> </template> <script> import ChildOne from '@/components/childOne.vue' import ChildTwo from '@/components/childTwo.vue' export default { components: { ChildOne, ChildTwo }, data() { return { type: 'child-one' } }, methods: { handleBtnClick() { this.type = (this.type === 'child-one' ? 'child-two' : 'child-one') } }, } </script>
2、v-once 指令:提高静态内容展示的效率
父组件:
<div class="box"> <ChildOne v-if="type === 'child-one'"/> <ChildTwo v-if="type === 'child-two'"/> <el-button type="primary" @click="handleBtnClick">change</el-button> </div>
子组件写法:
<template> <div v-once> <p class="size14">子组件 一</p> </div> </template>
【注】动态组件( component )的方法每一次切换,都是销毁一个组件加载另一个组件,在一定程度上是比较耗费性能的。
v-once指令,将组件直接放进内存,每一次切换不销毁组件,直接从内存中拿出历史加载过的组件。