vue插槽slot的使用示例

发布时间:2021-05-19 14:13:48 作者:小新
来源:亿速云 阅读:132

这篇文章将为大家详细讲解有关vue插槽slot的使用示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

vue中插槽的使用非常广泛,本文就插槽的使用和理解简单总结。

从字面理解插槽是预先插入一个代码空间,用于后期塞入数据。

插槽分类

匿名插槽     ------------------   匿名的代码空间

具名插槽     ------------------   带有命名的代码空间

作用域插槽 -------------------   带有数据的代码空间

插槽使用示例

匿名插槽

说明在组件中先定义预留的代码空间,组件在使用时直接写入代码

<template>
 <div class="child">
  <h4>这里是子组件</h4>
  <slot></slot>
 </div>
</template>

使用:

<template>
 <div class="father">
  <h4>这里是父组件</h4>
  <child>
   <div class="tmpl">
    <span>菜单1</span>
    <span>菜单2</span>
    <span>菜单3</span>
    <span>菜单4</span>
    <span>菜单5</span>
    <span>菜单6</span>
   </div>
  </child>
 </div>
</template>

具名插槽

预先在组件中定义一个带有名称的代码空间,使用组件时用:slot绑定名称

<template>
 <div class="child">
 // 具名插槽
 <slot name="up"></slot>
 <h4>这里是子组件</h4>
 // 具名插槽
 <slot name="down"></slot>
 // 匿名插槽
 <slot></slot>
 </div>
</template>

使用:

<template>
 <div class="father">
 <h4>这里是父组件</h4>
 <child>
  //插槽up
  <div class="tmpl" slot="up">
  <span>菜单1</span>
  <span>菜单2</span>
  <span>菜单3</span>
  <span>菜单4</span>
  <span>菜单5</span>
  <span>菜单6</span>
  </div>
  //插槽down
  <div class="tmpl" slot="down">
  <span>菜单-1</span>
  <span>菜单-2</span>
  <span>菜单-3</span>
  <span>菜单-4</span>
  <span>菜单-5</span>
  <span>菜单-6</span>
  </div>
  //匿名插槽
  <div class="tmpl">
  <span>菜单->1</span>
  <span>菜单->2</span>
  <span>菜单->3</span>
  <span>菜单->4</span>
  <span>菜单->5</span>
  <span>菜单->6</span>
  </div>
 </child>
 </div>
</template>

作用域插槽 (有数据,但放开了渲染)

在组件中预先定义一个带有数据资源的代码空间,使用组件时可以直接使用代码空间中的数据

定义

<template>
 <div class="child">
 
 <h4>这里是子组件</h4>
 // 作用域插槽
 <slot :data="data"></slot>
 </div>
</template>
 export default {
 data: function(){
  return {
  data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
  }
 }
}

使用

<template>
 <div class="father">
 <h4>这里是父组件</h4>
 <!--第一次使用:用flex展示数据-->
 <child>
  <template slot-scope="user">
  <div class="tmpl">
   <span v-for="item in user.data">{{item}}</span>
  </div>
  </template>
 
 </child>
 
 <!--第二次使用:用列表展示数据-->
 <child>
  <template slot-scope="user">
  <ul>
   <li v-for="item in user.data">{{item}}</li>
  </ul>
  </template>
 
 </child>
 
 <!--第三次使用:直接显示数据-->
 <child>
  <template slot-scope="user">
  {{user.data}}
  </template>
 
 </child>
 
 <!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽-->
 <child>
  我就是模板
 </child>
 </div>
</template>

匿名插槽和具名插槽的功能是 预留插入代码的空间

作用域插槽是提供数据资源,预留代码渲染逻辑空间

关于“vue插槽slot的使用示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. vue中插槽slot的使用方法
  2. slot插槽怎么在vue中使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue slot

上一篇:vue-cli3项目升级到vue-cli4的示例分析

下一篇:Visual Studio 2019 Vue项目的目录结构是怎样的

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》