动态组件&插槽

一、动态组件

1.动态组件指的是动态切换组件的显示与隐藏,作用:组件的占位符,is 属性的值表示渲染的组件的名字。

需求:点击 不同按钮 展现不同组件的页面

在这里插入图片描述
2.keep-alive的使用
点击按钮时,动态切换时会销毁组件,keep-alive保持缓存。组件被缓存时,自动触发 deactivated 生命周期函数;被激活时,自动触发 activated 生命周期函数。指定哪些组件被缓存可以使用 include 属性; 指定哪些组件不需要被缓存使用exclude属性

<template>
  <div>
    <div>
      <button @click="comName = 'Left'">展现 Left</button>
      <button @click="comName = 'Right'">展现 Right</button>
    </div>
    <div>
      <keep-alive include="Left">
        <component :is="comName"></component>
      </keep-alive>
    </div>
  </div>
</template>
<script>
import Left from '@/components/Left'
import Right from '@/components/Right'

export default {
    
    
  data(){
    
    
    return {
    
    
      comName:''
    }
  },
  components:{
    
    
    Left,
    Right
  }
}
</script>

二、插槽(Slot)

1.插槽是 vue 为组件封装者提供的能力,把不确定的用户自定义的部分定义为插槽。
2.把内容填充到指定名称的插槽使用 v-slot:name(简写 #),只能放在组件 或 template(虚拟标签) 里

// 组件.vue
<slot name="default">。。。</slot>

// 引用.vue
<组件 v-slot:default>。。。</组件>
----------------------------------------------
<template v-slot:default>。。。</template>
  • 具名插槽:起名字的
  • 作用域插槽:绑定数据的

猜你喜欢

转载自blog.csdn.net/weixin_52905182/article/details/127734902