slot内容分发

slot 内容分发:为了让组件可以组合,我们需要一种方式来混合父组件的内容与子组件自己的模板。

比如我们遇到组件需要相互嵌套这样的情况:
App.vue 文件

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

Hello.vue 文件

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

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

 
 

所以就需要用到 slot 插口,否则该组件标签中的内容将会被丢弃

一、 单个插槽

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

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

注意:<solt></slot> 标签内是可以自定义内容的,如果在调用的 <Hello></Hello> 标签内没有写入任何内容,则显示 <solt></slot> 标签内的自定义内容,否则显示在调用的 <Hello></Hello> 标签内写入的内容

二、多个插槽

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

App.vue 文件

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

Hello.vue 文件

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

最后渲染显示为


 
 
三、作用域插槽
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> 

渲染结果为:


 

猜你喜欢

转载自www.cnblogs.com/wu971023-/p/9037686.html