Vue插槽<slot>的探索

slot作为vue进行内容分发的重要组成,对其作用一直是模模糊糊的,今天研究了一下,特意记录一些体会,希望对阅读到的你有所帮助。


slot分为默认插槽、具名插槽和作用域插槽,默认插槽和具名插槽相对简单,上代码:
<!-- 在子组件中预留slot标签 -->
<template>
  <div class="hello">
    <!-- 默认插槽 -->
    <h1>这里是头部</h1>
    <slot></slot>

    <!-- 具名插槽 -->
    <h1>{{ msg }}</h1>
    <slot name="content"></slot>
    <h1>这里是底部</h1>
    <slot name="footer"></slot>
  </div>
</template>
<!-- 在父组件中填写子组件中的slot -->
<template>
  <div class="home">
    <HelloWorld  msg="这里是Content">
      <!-- 默认插槽 -->
      <template>
        <span class="text" v-for="item in nav" :key="item.id">
          {{ item.label }}
        </span>
      </template>
      <!-- 具名插槽 -->
      <template v-slot:content>
        <div class="text" @click="contentFn">
          这里是内容的具体内容
        </div>
      </template>
      <template v-slot:footer>
        <div class="text">
          这里是底部的具体内容
        </div>
      </template>
    </HelloWorld>
  </div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";

export default {
  name: "Home",
  components: {
    HelloWorld
  },
  data() {
    return {
      nav: [
        { label: "水果", id: 1 },
        { label: "旅游", id: 2 },
        { label: "国家", id: 3 },
        { label: "数码", id: 4 }
      ]
    };
  }
</script>
  • 默认插槽与具名插槽的最终效果


    浏览器效果

    F12 结构
总结:
  • 使用插槽时,要让插槽展示对应内容必须在子组件中预留slot标签,并且父组件中要填写slot内容。
  • 使用具名插槽时,父组件中的tempiate v-slot值必须对应子组件中slot标签上name属性值。
  • 如果子组件中有多个默认插槽,父组件中填写的内容将会被分发到所有的默认插槽,页面上展示多个父组件内容。

接下来将作用域插槽作为重点:

作用域插槽顾名思义带数据的插槽,在实际开发过程中,公用组件的内容一成不变是不可能的,所以这就要求插槽的内容也是动态数据。

<!-- 子组件中传递数据 -->
<template>
  <div class="hello">
    <!-- 作用域插槽 -->
    <h1>这里是作用域插槽</h1>
    <slot name="scope" :row="data"></slot>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  data() {
    return {
      data: [
        { name: "哈哈哈", id: 0, age: 1 },
        { name: "嘿嘿嘿", id: 1, age: 2 },
        { name: "呵呵呵", id: 2, age: 3 },
        { name: "啾啾啾", id: 3, age: 4 }
      ]
    };
  }
};
</script>
<!-- 父组件中接受、操作数据 -->
<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" @click="clickFn" />
    <HelloWorld>
      <!-- 作用域插槽 -->
      <template slot="scope" slot-scope="scoped">
        <div class="text">
          <div
            v-for="item in scoped.row"
            :key="item.id"
            @click="scopdeFn(item)"
          >
            {{ item.age }} {{ item.name }}
          </div>
        </div>
      </template> 
    </HelloWorld>
  </div>
</template>
  • 作用域插槽的最终效果


    image.png

    image.png

以上就是对vue插槽的粗鄙理解,如描述模糊,理解有误还请群公指正。

点赞就是爱!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容