slot默认插槽,具名插槽,作用域插槽

769 阅读1分钟

1.什么是插槽: 插槽就是子组件,提供给父组件的一个占位符它是在子组件中使用的标签,使用slot标签表示父组件可以在这个占位符中填充任何代码,如HTML,组件,填充的内容会替换掉子组件的slot标签

2.插槽分为3种不同的插槽分别是:

    1.默认插槽
    2.具名插槽 :子组件中可以有多个插槽给它们分别添加名字用于区分
    3.作用域插槽 :子组件中的数据通过插槽传递给父组件,然后显示在子组件中
    

3.默认插槽示例:

//在父组件中
<template>
  <div>
    <h1>我是父组件</h1>
    <Child>
        <p>插槽学习这里的内容显示在子组件的插槽中</p>
      <p>插槽第二条数据</p>
    </Child>
  </div>
</template>

<script>
import Child from "./children.vue";
export default {
  name: "father",
  components: { Child },
};
</script>


//在子组件中
<template>
  <div>
    <h3>我是子组件</h3>
    <!-- 写入插槽 -->
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "Child",
};
</script>

4.具名插槽示例 :

//在子组件中
<template>
  <div>
    <h3>我是子组件</h3>
    //插槽x
    <slot name="x"></slot>
    //插槽y
    <slot name="y"></slot>
  </div>
</template>
<script>
export default {
  name: "Child",
};
</script>


//在父组件中
<template>
  <div>
    <h1>我是父组件</h1>
    <Child>
         <template v-slot:x>
              <p>插槽学习这里的内容显示在子组件的x插槽中</p>
              <p>插槽第二条数据x</p>
         </template>
         <template v-slot:y>
              <h3>插槽学习这里的内容显示在子组件的y插槽</h3>
              <h3>插槽第二条数据y</h3>
         </template>
    </Child>
  </div>
</template>
<script>
import Child from "./children.vue";
export default {
  name: "father",
  components: { Child },
};
</script>

5.作用域插槽示例 :

//在子组件中
<template>
  <div>
    <h3>我是子组件</h3>
    <slot name="x" :mes="content"></slot>
  </div>
</template>
<script>
export default {
  name: "Child",
  data() {
    return {
      content:'有个简单的问题什么是爱情'
    }
  },
};
</script>


//在父组件中
<template>
  <div>
    <h1>我是父组件</h1>
    <Child>
     <template v-slot:x="z">
      <p>插槽学习这里的内容显示在子组件的x插槽中</p>
      <p>{{z.mes}}</p>
     </template>
    </Child>
  </div>
</template>
<script>
import Child from "./children.vue";
export default {
  name: "father",
  components: { Child },
};
</script>