vue的插槽

119 阅读2分钟

大家好,我是大帅子,今天给大家讲一下vue插槽的基本使用,下面我们直接开始


插槽基本用法

  1. 插槽的作用 : 父 -> 子 html的结构
  2. 插槽的使用 :
    (1) 子组件里面使用 <slot></slot> 先占位
    (2) 父组件传递插槽 <子组件> 传递HTML结构 </子组件>
例 :
// 子组件
<template>
  <div class="son">
    <slot> 我是slot默认数据 </slot>
  </div>
</template>
// 父组件
<template>
  <div id="app">
    <h1>我是父组件</h1>

    <Goods> 啦啦啦</Goods>

    <Goods> <button disabled>卖完了</button> </Goods>

    <Goods></Goods>
  </div>
</template>

<script>
//导入局部组件
import Goods from "./components/goods";

export default {
  data() {
    return {};
  },
  components: {
    Goods,
  },
};
</script>

<style>
#app {
  border: 1px solid #000;
}
</style>

最后的呈现结果 : 如果插槽里面传入了HTML的话,就会覆盖默认的样式,没有传入HTML结构 就还是会显示默认的样式

image.png

具名插槽

  1. 具名插槽的作用 : 父 -> 子 多个不同的HTML结构

  2. 插槽的使用 :
    (1) 子组件里面使用 <slot></slot> 先占位 ,但是要先提前设置每个插槽的 name 属性

     <slot name="插槽名"></slot>
     
    

    (2) 父组件传递插槽 格式如下
     <template #插槽名>
         <子组件>
             要传递的HTML结构
         </子组件>
     </template>
    

例 :

// 子组件
<template>
 <div class="cell">
   <div class="title">
     <slot name="title"> ... </slot>
   </div>
   <div class="content">
     <slot name="content"> 111 </slot>
   </div>
   <div class="right">
     <slot name="right"> 222 </slot>
   </div>
 </div>
</template>

<script>
export default {};
</script>

<style>
.cell {
 border: 1px solid #f00;
 height: 60px;
 padding: 10px;
 position: relative;
}

.title {
 float: left;
}

.content {
 position: absolute;
 bottom: 10px;
 left: 10px;
}

.right {
 float: right;
}
</style>
// 父组件
<template>
 <div id="app">
   <h1>我是父组件</h1>

   <Cell>
     <template v-slot:title>
       <h3>我是标题</h3>
     </template>
     <template #content>
       <strong> 我是内容 </strong>
     </template>
     <template #right>
       <i>我是字体图标</i>
     </template>
   </Cell>
 </div>
</template>

<script>
import Cell from "./components/cell.vue";
export default {
 data() {
   return {};
 },
 components: {
   Cell,
 },
};
</script>

<style>
#app {
 border: 1px solid #000;
}
</style>

最后的呈现结果 : 就会每个具名插槽对应覆盖不同的内容

image.png

作用域插槽

  1. 具名插槽的作用 : 父组件 -> 子组件 传递插槽 时,可以使用子组件内部的数据

  2. 具名插槽的使用 :

    (1) 子组件里面 : <slot :属性名="属性值">默认content</slot> (属性名我看见之前的官网都是叫scope,现在虽然删除了,但是我还是推荐大家看过我这边文章的就怀旧一下,哈哈)
    (2) 父组件里面 : <子组件> </子组件>

      <子组件>
          <template v-slot="对象名">
              HTML内容
          </template>
      </子组件>
    

是不是还是蛮简单的

作用域插槽跟 $emit 的 异同

作用域插槽和$emit异同点

​ 相同点:都是子传父

​ 不同点:

​ $emit : 子传父的数据通过事件来接收

​ 作用域插槽:子传父的数据是通过插槽v-slot接收 (子传父的数据,只能给插槽用)


好了,这边已经给大家介绍到这里,以上是我自己的理解,希望可以帮到大家, 欢迎留言我这边一定会第一时间给大家解答,喜欢的可以点赞收藏
🐣---->🦅         还需努力!大家一起进步!!!