slot内容分发

slot 内容分发:为了让组件能够组合,咱们须要一种方式来混合父组件的内容与子组件本身的模板。javascript

好比咱们遇到组件须要相互嵌套这样的状况:
App.vue 文件css

<template> <div class="app"> <Hello> <World></World> <Vue></Vue> </Hello> </div> </template> 

Hello.vue 文件html

<template> <div class="hello"> <h3>我是 hello 组件</h3> </div> </template> 

那这么直接写是确定只显示 <Hello> 组件的内容
vue

 
 

 

因此就须要用到 slot 插口,不然该组件标签中的内容将会被丢弃java

1、 单个插槽

只须要在 Hello.vue 文件内写入 <solt></slot> 标签json

<template> <div class="hello"> <h3>我是 hello 组件</h3> <slot>此处可自定义内容,若是该组件的标签内没有内容,则显示此内容</slot> </div> </template> 
 
 

注意:<solt></slot> 标签内是能够自定义内容的,若是在调用的 <Hello></Hello> 标签内没有写入任何内容,则显示 <solt></slot> 标签内的自定义内容,不然显示在调用的 <Hello></Hello> 标签内写入的内容app

2、多个插槽

假如咱们想要改变 <Hello></Hello> 组件内 <World></World><Vue></Vue> 的显示位置,就能够用到一个特殊的特性 name 来进一步配置如何分发内容,多个插槽能够有不一样的名字。具名插槽将匹配内容片断中有对应 slot 特性的元素。仍然能够有一个匿名插槽,它是默认插槽,做为找不到匹配的内容片断的备用插槽。若是没有默认插槽,这些找不到匹配的内容片断将被抛弃。ide

App.vue 文件ui

<template> <div class="app"> <Hello> <World slot="world"></World> <h5>我是备用插槽内部显示的内容</h5> <Vue slot="vue"></Vue> </Hello> </div> </template> 

Hello.vue 文件spa

<template> <div class="hello"> <slot name="vue"></slot> <h3>我是 hello 组件</h3> <slot name="world"></slot> <slot></slot> </div> </template> 

最后渲染显示为


 
 
3、做用域插槽
1. 做用域插槽是一种特殊类型的插槽,用做一个 (能被传递数据的) 可重用模板,来代替已经渲染好的元素。

在子组件中,slot 插槽还能够用做传递数据,相似于用 prop 来传递数据

在子组件 Hello.vue 中,只须要将须要传递的内容写入插槽中

<template> <div class="hello"> <h3>我是 hello 组件</h3> <!-- text 和 text1 是自定义的,能够随便写 --> <slot text="我是hello" text1="组件的数据"></slot> </div> </template> 

<slot text="我是hello" text1="组件的数据"></slot> 至关于被渲染为

{
    text:'我是hello', text1:'组件的数据' } 

在 App.vue 中调用 Hello 组件时,经过在 template 中写入 slot-scope 特殊属性来获取数据

<template> <div class="app"> <Hello> <!-- template 是该做用域插槽的模版, slot-scope是一个特殊属性,用来接收 hello 组件中插槽传过来的值 --> <template slot-scope="hello"> <!-- 经过访问一个 json 的方式访问 hello 中 slot 传过来的值 --> <span>{{hello.text}} + {{hello.text1}}</span> </template> </Hello> </div> </template> 

注意:在 vue 2.5.0以上版本,就不须要用到 template 模板了,slot-scope 能够做用在任意元素中

被渲染的结果为:


 
 

 
 
2. 更典型的用例是在列表组件中,容许使用者自定义如何渲染列表的每一项

在 App.vue 组件内

<template> <div class="app"> <!-- 在子组件绑定 items 把父组件的数据传给子组件 --> <Hello :items="items"> <li slot="item" slot-scope="bbb"> {{ bbb.text }} </li> </Hello> </div> </template> <script> // 引入 Hello 组件 import Hello from './assets/components/Hello.vue' export default { data(){ return { items:[ {text:'aaaaaa'}, {text:'bbbbb'} ] } }, // 注册 Hello 组件 components:{ Hello } } </script> 

在 Hello.vue 组件中

<template> <div class="hello"> <ul> <!-- 此处的 items 为父组件传过来的数据 --> <!-- text 为 item 内的对应数据,由于 items 是一个对象,因此要用到绑定,不然页面上直接渲染出来的内容为 item.text --> <slot name="item" v-for="item in items" text="item.text"></slot> </ul> </div> </template> <script> export default { // 接收父组件传过来的 items 数据 props: ['items'], } </script> 

渲染结果为:


 
相关文章
相关标签/搜索