Vue2.0五——props和slot

发布时间:2019-05-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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> 
    
    
    
    

脚本宝典总结

以上是脚本宝典为你收集整理的Vue2.0五——props和slot全部内容,希望文章能够帮你解决Vue2.0五——props和slot所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue