5.vue3 动态组件 插槽

581 阅读1分钟

动态组件

动态组件就是根据组件的名字来渲染组件

<div id="box">
        <!-- 动态组件在切换的时候会引起组件的挂载和卸载 -->
        <button @click="cname='List'">评论列表</button>
        <button @click="cname='PublicComments'">发布评论</button>
        <!-- keep-alive 缓存组件   用这个进行缓存数据,而且动态组件在在切换时就不在挂载和卸载了 -->
        <keep-alive>
             <component :is="cname"></component>
         </keep-alive>
    </div>

activated keep-alive缓存的组件 启用缓存的时候调用

deactivated keep-alive缓存的组件 停用缓存的时候调用

插槽

<div id="box">
        {{str}}
        <Com>  
            <!-- 组件开始和结束标记中间是插槽的内容  -->
            <template v-slot:default>
                 <span>用户名</span>
            </template>
            <template #btn="props">
                <button @click="receive(props.n)">添加 </button>
           </template>
        </Com>
    </div>

        let Com={
            data(){
                return {
                    txt:""
                }
            },
            //没有名字的插槽叫匿名插槽  有名字的插槽叫具名插槽  可以携带数据的插槽叫作用域插槽或数据插槽
            template:`<div><slot></slot><input type="text" v-model="txt" />
                <slot name="btn" :n="txt"></slot></div>`
        }