vue2中插槽(slot)的基本使用规范

Emma ·
更新时间:2024-09-20
· 952 次阅读

目录

前言

基础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使用规范内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



VUE slot

需要 登录 后方可回复, 如果你还没有账号请 注册新账号