vue2中插槽(slot)的基本使用规范
作者:程序猿布欧
插槽(Slot)是Vue提出来的一个概念,正如名字一样,插槽用于决定将所携带的内容,插入到指定的某个位置,从而使模板分块,具有模块化的特质和更大的重用性,下面这篇文章主要给大家介绍了关于vue2中插槽(slot)的基本使用规范的相关资料,需要的朋友可以参考下
前言
在vue的开发过程中,我们会经常使用到vue的slot插槽组件,vue官方文档的描述:
Vue 实现了一套内容分发的 API,这套 API 的设计灵感源自 Web Components 规范草案,将元素作为承载分发内容的出口
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
总结
到此这篇关于vue2中插槽(slot)的基本使用规范的文章就介绍到这了,更多相关vue2中slot使用规范内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
