让前端飞vueWeb前端之路

vue插槽<作用域插槽>

2019-05-29  本文已影响2人  zz77zz

2019年5月29日07:51:57
插槽 - 这里之前没怎么注意 这次算是懂了个大概

作用域插槽 应用场景 当子组件循环或者dom结构需要外部父子间传递的时候用

必须使用 template标签 -> slot-scope接收 ->slot定义属性传递值给template 就这三部其实

代码如下

<!DOCTYPE html>
<html>
<head>
    <title>test for vue</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <!-- 4-5 -->
    <!-- <h3>非父子组件间传值(Bus/总线/发布订阅模式/观察者模式)</h3>
    <child content="Dad gives u"></child>
    <child content="This money"></child> -->
    <!-- 4-6/4-7 -->
    <h3>插槽 slot/作用域插槽</h3>
    <child>
        <!-- <h4>这里是子组件需要插槽的part</h4> -->
        <div class="header" slot="header">Header 网页头</div>
        <div class="footer" slot="footer">Footer 网页脚</div>
    </child>

    <test_for_slot>
        <template slot-scope="SlotData">
        <h2>{{SlotData.thisis_shuxing}}</h2>
        </template>
    </test_for_slot>

</div>
<script type="text/javascript">

// 4-5
// // 非父子组件 用总线机制 其实就是给vue挂了个全局的属性
// Vue.prototype.bus = new Vue()

//  Vue.component('child',{
//      props:{
//          content:String
//      },
//      data(){
//          return {
//              selfContent:this.content
//          }
//      },
//      template:'<div @click="handleClick">{{selfContent}}</div>',
//      methods:{
//          handleClick(){
//              // alert(this.content)
//              this.bus.$emit('explode_func',this.selfContent)
//          }
//      },
//      mounted:function(){
//          var _that = this
//          this.bus.$on('explode_func',function(msg){
//              alert(msg) //这里会跳出两次 以为组件有两个 都监听了方法
//              _that.selfContent = msg
//          })
//      }
//  })

4-6

    Vue.component('child',{
        props:['content'],
        template:`
                    <div>
                        <slot name="header">
                            <h4>如果插没有传值 默认显示内容
                            </h4>
                        </slot>

                        <div>中间内容</div>

                        <slot name="footer"></slot>
                    </div>
                 `
    })

    Vue.component('test_for_slot',{
        data:function(){
            return {
                list:['a','b','c','d']
            }
        },
        template:`<div>
                    <ul>
                    <slot v-for="item of list"
                            :thisis_shuxing=item
                    >
                         {{item}}
                    </slot>
                    </ul>
                </div>`
    })

    var app = new Vue({
        el:"#app"
    })

</script>
</body>
</html>

Slot肯定还有别的使用场景 只是没有讲到 以后项目遇到了再做个总结

下一节是动态组件跟v-once指令

上一篇 下一篇

猜你喜欢

热点阅读