美文网首页Vuevue
vue学习笔记--插槽、具名插槽和作用域插槽

vue学习笔记--插槽、具名插槽和作用域插槽

作者: 持续5年输出bug | 来源:发表于2018-08-21 07:46 被阅读141次

插槽使用场景是;如果子组件需要显示的内容并非来自本身,而是父组件传递进来的,而假如直接这样写,是不可以实现的,因为如果me-component没有包含一个 <slot> 元素,则任何传入它的内容都会被抛弃:


image.png

要实现上面的使用场景,可以利用插槽实现:

<div id="app">
<me-component>
<h1>我是header</h1>
</me-component>
</div>
<script >
Vue.component('me-component', {
template:
<div> <p>你好</p> <slot></slot> </div>
})
var vm = new Vue({
el:"#app"
})

但是,假如使用多个插槽的时候,就需要用具名插槽

<div id="app">
    <me-component>
        <h1 slot="header">我是header</h1>  
        <h1 slot="footer">我是footerr</h1>
    </me-component>
</div>

<script >
Vue.component('me-component', {
template:
<div> <p>你好</p> <slot name="header"></slot> <slot name="footer"></slot> </div>
})
var vm = new Vue({
el:"#app"
})

另外slot 插槽还可以定义默认值,如果父组件没有对应的插槽标签,那么deom上显示的是<slot ></slot> 标签里的内容

20180820165846.png
20180820165856.png 20180820165846.png

以上代码,slot 特性的也可以直接用在一个普通的元素上。这样的话template标签对就可以去掉了

<h1 slot-scope="resave" >{{resave.item}}</h1>

效果图:


20180820172853.png

相关文章

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

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

  • vue----slot插槽

    插槽分类 匿名插槽 具名插槽 作用域插槽

  • 2.插槽

    匿名插槽 具名插槽 作用域插槽

  • vue3中的插槽

    插槽 默认插槽 具名插槽,v-slot可以简写为# 动态插槽 #[dynamicSlotName] 作用域插槽(...

  • vue中slot插槽的使用

    插槽的种类:1、默认插槽、具名插槽、作用域插槽、解构插槽、动态插槽几种。转原文:https://www.jians...

  • vue插槽之$slots、$scopedSlots

    在学习vue插槽的时候,将匿名插槽,具名插槽,作用域插槽都实践了一遍,但是却碰到一些问题,请看代码子组件: 父组件...

  • vue 插槽

    插槽语法是Vue实现的内容分发API,用于复合组件开发。 匿名插槽 具名插槽 作用域插槽 将内容分发到子组件指定位置

  • Vue-使用插槽

    二。具名卡槽 作用域插槽:插槽循环时使用

  • slot 用法以及使用场景

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

  • 插槽

    默认插槽: 具名插槽:slot name='footer' 作用域插槽:v-slot===slot-scope 默...

网友评论

    本文标题:vue学习笔记--插槽、具名插槽和作用域插槽

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