Vue.js的组件中的slot和props

摘要:props是用来接收参数的 例如父组件向子组件传参 可以放在props中;插槽 slot分发模式主要用于在组件中插入标签或者组件之间的相互嵌套,个人认为如果组件中有需要单独定义的地方可以使用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> 

来源:https://segmentfault.com/a/1190000012314707


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_413