前言
接上篇学习笔记,分享3个内置组件:动态组件、缓存组件、分发组件基本用法。大家一起通过code的示例,从现象理解,注意再次理解生命周期。
一、code示例
组件A:CompA
<script setup>
import {onMounted, onUnmounted} from "vue";//再次理解生命周期const compFun = () => {console.log("我是组件A");
}
//vue3,setup相当与created
compFun();onMounted(() => {console.log("组件A挂载");
});onUnmounted(() => {console.log("组件A销毁");
});</script><template><div class="compA"><h1>我是组件A</h1></div></template><style scoped>
.compA{align-content: center;
}</style>
组件B:CompB
<script setup>
import {onMounted, onUnmounted} from "vue";const compFun = () => {console.log("我是组件B");
}
//vue3,setup相当与created
compFun();onMounted(() => {console.log("组件B挂载");
});onUnmounted(() => {console.log("组件B销毁");
});
</script><template><div class="CompB"><h1>我是组件B,我有插槽</h1><slot></slot></div>
</template><style scoped>
.CompB{align-content: center;
}</style>
主页面AppMain.vue
<script setup>
import {ref, defineOptions} from 'vue';
import CompA from './components/CompA.vue';
import CompB from './components/CompB.vue';//vue3不这样定义,会切换无效,但是compName的值却是改变的
defineOptions({components: {CompA,CompB}
})// ref创建响应式数据
const compName = ref('CompA');//
const slotContent = ref("");function changeComp(changeCompName) {console.log("原组件:", compName.value, "新组件:", changeCompName);compName.value = changeCompName;if (changeCompName === 'CompB') {slotContent.value = "<div><hr><h1>我是插槽内容</h1></div>";}
}</script><template><div class="App2"><h1>我是App2父组建</h1><button @click="changeComp('CompA')">组件A</button><button @click="changeComp('CompB')">组件B</button><hr><h1>动态组件切换展示区域,当前组件:{{ compName }}</h1><!-- 缓存组件:缓存非活动组件 --><keep-alive><component v-bind:is="compName"><div v-html="slotContent"></div></component></keep-alive></div>
</template><style scoped>
.App2 {align-content: center;
}
</style>
main.js
import { createApp } from 'vue'
//import App from './App.vue'
import AppMain from './AppMain.vue'createApp(AppMain).mount('#app')
二、现象截图
1.初始化
2、点击按钮B
3、点击按钮A
- console打印就这些,后面你再怎么点击,组件不会重新销毁、挂载了,这就是缓存组件的妙。
- 插槽标签呢?slot
总结
- 基本上动态组件跟子组件上加if、else逻辑一样,可能用的少
- 缓存组件有编译奇葩问题,大家可以自己试着在“keep-alive”标签体内写注释试试,你会发现编译不通过
笔记就记到这里,我们一起晚上睡梦中再理解下,uping!