Vue2.0五——props和slot

props

props是用来接收参数的 例如父组件向子组件传参 可以放在props中

slot

slot:插槽 slot分发模式主要用于在组件中插入标签或者组件之间的相互嵌套
个人认为如果组件中有需要单独定义的地方 可以使用slot

单个slot 内容分发 可以选择用slot标签事先占个位置

例子:

现在父组件中占个位置
   <template id="a">
    <div>hello!</div>
    <slot>没有内容 就显示这个</slot>
</template>

var a = Vue.extend({
    template: '#a'
})

子:
<div id="child">
    <A></A>
    <hr/>
    <A>
        <h1>内容1</h1>
        <h1>内容2</h1>
    </A>
</div>
var child = new Vue({
    el: '#child',
    components: {
        "A":A
    }
})
结果:
    hello!
    没有内容 就显示这个
    
    hello!
    内容1
    内容2

具名Slot

<template id="b">
    <slot name="slot1"></slot>
    <slot></slot>
    <slot name="slot2"></slot>
</template>

var B = Vue.extend({
    template: "#b"
});

<div id="child2">
    <B>
        <div slot="slot1">this is slot01</div>
        <div slot="slot2">this is slot02</div>
        <div>aaa</div>
        <div>bbb</div>
    </B>
</div>   

var child2 = new Vue({
    el: "#child2",
    components: {
        "B": B
    }
});

结果:
    this is slot01
    aaa
    bbb
    this is slot02

作用域插槽 用来传参

子=> 父

子:
<slot name="b" :msg="hello"></slot>

父:
<template slot="b" **slot-scope**="props">
    <child>
        <div class="">
           {{props.msg}}
        </div>
    </child>
</template>       
   

作用域插槽更典型的用例是在列表组件中,允许使用者自定义如何渲染列表的每一项:

<mylist :items="items">
  <!-- 作用域插槽也可以是具名的 -->
  <li
    slot="item"
    slot-scope="props"
    class="my-fancy-item">
    {{ props.text }}
  </li>
</mylist>
列表组件的模板:
<ul>
  <slot name="item"
    v-for="item in items"
    :text="item.text">
    <!-- 这里写入备用内容 -->
  </slot>
</ul> 
    
    
    
    
    原文作者:Cymiran
    原文地址: https://segmentfault.com/a/1190000012314707
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞