在Vue中使用插槽

在Vue中使用插槽

组件的template里可以在任意位置添加<slot></slot>,slot为标签,称为插槽,像是一个借口,接受html数据。

具名插槽,slot标签可以添加name属性,用与区分组件中不同插槽

<slot name="header"></slot>

<slot name="header">默认值</slot>

这样在调用组件时就可以在innerHTML里写入对应的html数据

<div slot="header"></div>这样就会把这个标签下的,包括这个标签,所有html元素替换到<slot name="header"></slot>的位置,本质和v-html没什么区别。

<body>
  <div id="root">
    <child content="Dell"></child>
    <child content="Lee"></child>
  </div>
  <script>
    Vue.prototype.bus=new Vue()
    Vue.component('child',{
      data:function(){
        return{
          selfContent:this.content
        }
        
      },
      props:{
        content:String,
      },
      template:'<div @click="handleClick">{{ selfContent}}</div>',
      methods:{
        handleClick:function(){
          //alert(this.content)
          this.bus.$emit('change',this.selfContent)

        }
      },
      mounted:function(){
        var this_=this
        this.bus.$on('change',function(msg){
         this_. selfContent=msg
        })
      }
    })
    var vm=new Vue({
      el:'#root'
    })
  </script>
 
</body>
posted @ 2019-12-19 21:07  嘘,在学习呢  阅读(198)  评论(0编辑  收藏  举报