关于vue.js:vue2版本中slot的基本使用详解

前言

在vue的开发过程中,咱们会常常应用到vue的slot插槽组件,vue官网文档的形容:

Vue 实现了一套内容散发的 API,这套 API 的设计灵感源自 Web Components 标准草案,将 <slot> 元素作为承载散发内容的进口

slot大略分为以下几种:

根底slot组件(匿名插槽)

匿名插槽次要应用场景并不波及特地简单的业务,更像是纯展现组件内容

<!--子组件-->

<template>
    <span>
        我是根底slot子组件, 父组件传过来的值:
        <span style="color: red"><slot></slot></span>
    </span>
</template>
<!--父组件-->

<li>
    根底slot组件(匿名插槽):<Base>这是一段父组件传过来的文字</Base>
</li>

import Base from "./Base.vue";

具名插槽

具名插槽,须要在父组件和子组件约定插槽名称

<!--子组件-->

<template>
    <span>
        <span style="color: red">
            <slot name="name1"></slot>
            <slot name="name2"></slot>
        </span>
    </span>
</template>
<!--父组件-->

<li>
    <p>具名插槽:</p>
    <Specific>
        <template v-slot:name1>
            <p>name1传过来的内容</p>
        </template>
        <template v-slot:name2>
            <p>name2传过来的内容</p>
        </template>
    </Specific>
</li>

import Specific from "./Specific.vue";

作用域插槽

作用域插槽,子组件提供数据,父组件接管子组件的值并展现和解决逻辑

<!--子组件-->

<template>
    <span>
        <span>
            <slot name="scopeName" v-bind:scopeData="age"></slot>
        </span>
    </span>
</template>

<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";

@Component
export default class Scope extends Vue {
    private age: Number = 23;
}
</script>
<!--父组件-->

<li>
    <p>作用域插槽</p>
    <Scope>
        <template v-slot:scopeName="childData">
            作用域子组件slot返回的数据:
            <span style="color: red">
                {{ childData.scopeData }}
            </span>
        </template>
    </Scope>
</li>

import Specific from "./Specific.vue";

解构插槽

解构插槽,相似在js书写对象过程中的对象解构

{ data:{ username:1 } }
<!--子组件-->

<template>
    <span>
        <p>
            <slot v-bind:user="user"></slot>
        </p>
    </span>
</template>

<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";

@Component
export default class Deconstru extends Vue {
    private user: Object = {
        name: "zhangsan",
        age: 23,
    };
}
</script>
<!--父组件-->

<li>
    <p>解构插槽</p>
    <Deconstru>
        <template v-slot="{ user: person }">
            父组件模板:{{ person.name }},{{ person.age }}
        </template>
    </Deconstru>
</li>

import Specific from "./Deconstru.vue";

以上例子均已上传至开源仓库,后续对于vue的学习笔记均会更在在该我的项目上,欢送star

  • 码云 https://gitee.com/lewyon/vue-note
  • githup https://github.com/akari16/vue-note

总结

在vue的插槽文档中,还有蕴含

  • 独占默认插槽
  • 动静插槽名
  • 具名插槽的缩写

    <template #footer>
      <p>Here's some contact info</p>
    </template>

具体对于插槽的官网文档传送门

https://cn.vuejs.org/v2/guide…

文章集体博客地址:vue2版本中slot的根本应用详解

创作不易,转载请注明出处和作者。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理