美文网首页
Vue插槽slot

Vue插槽slot

作者: Kevin_hoo | 来源:发表于2019-07-19 17:52 被阅读0次

Vue 实现了一套内容分发的 API,将 <slot>元素作为承载分发内容的出口。大致如下
parent为父组件,child为子组件

  • 普通插槽

<template>
    <div class="parent">
        <com-child>
            <!-- 父组件在子组件里面插入标签,然后子组件引用slot就可以看到插槽内容 -->
            <span>{{msg}}</span> 可以不用标签
        </com-child>
    </div>
</template>

msg:'父组件普通插槽'
<template>
    <div class="child">
        <!-- 默认/default插槽 -->
        <slot>父组件没有插入内容时,此内容会显示,否则会被插入的内容覆盖</slot>
    </div>
</template>

显示效果:
父组件普通插槽 可以不用标签

  • 具名插槽

注意:v-slot是新指令,代替slot和slot-scope,版本需要在 2.6.0 以上

<template>
    <div class="parent">
        <com-child>
            <template slot=first>
                <div>这是第一个具名插槽</div>
            </template>
            <div slot='second'>这是第二个具名插槽</div>
            <template v-slot:third>
                <p>这是第三个具名插槽</p>
            </template>
        </com-child>
    </div>
</template>
<template>
    <div class="child">
        <slot name='first'>first</slot>
        <slot name='second'>second</slot>
        <slot name='third'>third</slot>
    </div>
</template>

显示效果:
这是第三个具名插槽
这是第一个具名插槽
这是第二个具名插槽
third

当前vue版本为: "^2.5.2",导致子组件中的third也显示出来了

  • 作用域插槽

父组件可以控制插槽的内容,能够访问子组件中才有的数据
注意:scope在2.5.0中被slot-scope替代,用法:除了scope只可以用于<template>元素,其他和slot-scope都相同

<template>
    <div class="parent">
        <template slot=itemSlot slot-scope="slotProps">
            <li>{{slotProps.itemid + ' & ' + slotProps.text}}</li>
        </template>
    </div>
</template>
<template>
    <div class="child">
        <slot name="itemSlot" v-for="item in items" 
          :text="item.text" 
          :itemid="item.id">
          默认值
        </slot>
    </div>
</template>

items:[
  {id:1,text:'第1段'},
  {id:2,text:'第2段'},
  {id:3,text:'第3段'},
]

显示效果:
1 & 第1段
2 & 第2段
3 & 第3段

相关文章

  • Vue之深入理解插槽—slot, slot-scope, v-s

    Vue 2.6.0 以前Vue 2.6.0 以后具名插槽 slot具名插槽 v-slot作用域插槽 slot-sc...

  • vue插槽

    vue插槽slot的理解与使用 vue slot插槽的使用介绍及总结

  • vue中的slot(插槽)

    vue中的插槽————slot 什么是插槽? 插槽(Slot)是Vue提出来的一个概念,正如名字一样,插槽用于决定...

  • vue 插槽的使用

    vue 插槽手册 深入理解vue中的slot与slot-scope 插槽的使用其实是很简单首先要明白插槽是使用在子...

  • 18、Vue3 作用域插槽

    作用域插槽:让插槽内容能够访问子组件中,vue2中作用域插槽使用slot-scope,vue3中使用v-slot ...

  • vue3-slot-消息框-模态框

    1.前言 1.使用vue3 的slot插槽时,大部分和vue2-slot插槽[https://www.jiansh...

  • slot是什么?有什么作用?原理是什么?

    slot又名插槽,是Vue的内容分发机制,组件内部的模板引擎使用slot元素作为承载分发内容的出口。插槽slot是...

  • slot(插槽)

    slot又称插槽,是Vue的内容分发机制,组件内部的模板引擎使用slot元素作为承载分发内容的出口。插槽slot是...

  • slot 用法以及使用场景

    Vue的插槽slot,分为3种 匿名插槽 具名插槽 作用域插槽 前两种很好理解,无非就是子组件里定义一个slot占...

  • Vue中Slot的渲染过程

    Vue在通过compiler解析模版中的slot, slot是组件中的插槽,通过解析slot,把slot的name...

网友评论

      本文标题:Vue插槽slot

      本文链接:https://www.haomeiwen.com/subject/qncslctx.html