打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
sot

一 什么是slot

slot可以将html从父组件传入子组件。

二 单个插槽(默认插槽,匿名插槽)

单个插槽可以放置在组件的任意位置,但是就像它的名字一样,一个组件中只能有一个该类插槽。
假定 my-component 组件有如下模板:

<div>  <h2>我是子组件的标题</h2>  <slot>    只有在没有要分发的内容时才会显示。  </slot></div>

父组件模板:

<div>  <h1>我是父组件的标题</h1>  <my-component>    <p>这是一些初始内容</p>    <p>这是更多的初始内容</p>  </my-component></div>

渲染结果:

<div>  <h1>我是父组件的标题</h1>  <div>    <h2>我是子组件的标题</h2>    <p>这是一些初始内容</p>    <p>这是更多的初始内容</p>  </div></div>

三 具名插槽

可以用一个特殊的特性 name 来进一步配置如何分发内容。多个插槽可以有不同的名字。具名插槽将匹配内容片段中有对应 slot 特性的元素。
仍然可以有一个匿名插槽,它是默认插槽,作为找不到匹配的内容片段的备用插槽。如果没有默认插槽,这些找不到匹配的内容片段将被抛弃。
假定 app-layout 组件有如下模板:

<div class="container">  <header>    <slot name="header"></slot>  </header>  <main>    <slot></slot>  </main>  <footer>    <slot name="footer"></slot>  </footer></div>

父组件模板:

<app-layout>  <h1 slot="header">这里可能是一个页面标题</h1>  <p>主要内容的一个段落。</p>  <p>另一个主要段落。</p>  <p slot="footer">这里有一些联系信息</p></app-layout>

渲染结果:

<div class="container">  <header>    <h1>这里可能是一个页面标题</h1>  </header>  <main>    <p>主要内容的一个段落。</p>    <p>另一个主要段落。</p>  </main>  <footer>    <p>这里有一些联系信息</p>  </footer> </div>

四 作用域插槽

作用域插槽就是 “带数据的插槽”,插槽作用域则是子组件给父组件提供数据,父组件提供样式。
下面的例子,你就能看到,父组件提供了三种样式(分别是flex、ul、直接显示),都没有提供数据,数据使用的都是子组件插槽自己绑定的那个数组(一堆人名的那个数组):

<template>  <div class="father">    <h3>这里是父组件</h3>    <!--第一次使用:用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>

子组件:

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

输出:

来源:http://www.icode9.com/content-4-240251.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
深入理解vue中的slot与slot
聊聊 VueJs 组件化编程
具名插槽、作用域插槽的新写法
通过UI库深入了解Vue的插槽的使用技巧(片尾有彩蛋)
vue入门基础教程之经验总结篇(小白入门必备)|建议收藏
详解vue组件三大核心概念
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服