Vue插槽

插槽

作用

让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件 => 子组件

分类

  1. 默认插槽
  2. 具名插槽
  3. 作用域插槽

使用方法

默认插槽

//父组件中
<Category>
      <div>html结构</div>
</Category>

//子组件中
<template>
  <div>
    <!-- 定义一个插槽 -->
    <slot>我是默认值,当使用者没有传递具体结构时,我会出现</slot>
  </div>
</template>

具名插槽

//父组件
<Category>
      <div slot="center">html结构</div>
      <!-- v-slot只能用在template标签 -->
      <!-- template可以包裹多层html结构,且不生成真实DOM元素,可以省一层结构 -->
      <template v-slot:footer>
        <div>html结构</div>
        <h4>html结构</h4>
      </template>
</Category>

//子组件
<template>
  <div>
    <slot name="center"></slot>
    <slot name="footer"></slot>
  </div>
</template>

作用域插槽

  1. 理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定(games数据在Categoty组件中,但用哪种html结构展示数据由App组件决定)。
//父组件
<Category>
      <template v-slot="{games}">
	//生成的是ol有序列表
        <ol>
        <li v-for="(item, index) in games" :key="index">{{ item }}</li>
      </ol>
      </template>
</Category>

<Category>
      <template v-slot="{games}">
	//生成的是h4标题
        <h4 v-for="(item, index) in games" :key="index">{{ item }}</h4>
      </template>
    </Category>

//子组件
<template>
  <div>
    <slot :games="games"></slot>
  </div>
</template>
...
//数据在Category自身
<script>
...
data() {
    return {
      games: ['红色警戒', '穿越火线', '劲舞团'],
    }
  },
}
...
</script>

ps:这两种写法都弃用了。

 <template slot-scope="{games}"></template>
 <template scope="{games}"></template>

现在用

<template v-slot="{games}"></template>
posted @ 2023-04-21 07:47  月豕  阅读(18)  评论(0)    收藏  举报