Vue中的slot

什么是插槽?

插槽就是在你子组件的模板里可以开辟一个或多个槽,让其他一些内容可以插入进来,称之为插槽。

为什么要使用插槽?

new Vue({
  el:"#app",
  template:`<div>
               <child>我想让这一行字显示出来</child>
            </div>`,
  components:{
    child:{
      template:`<h1>子组件</h1>`
    }
  }
})

我们想在上面的<child></child>标签里面写了一句话,但是发现页面上没有显示出来。
如果你想让他显示出来呢?这时候我们就需要用到插槽了。

插槽分为4点:

1 . 插槽可以插入哪些内容
2 . 匿名插槽
3 . 具名插槽
4 . 作用域插槽



一、插槽可以插入哪些内容

可以是不同种类的节点
new Vue({
  el:"#app",
  template:`<div>
               <child>我是一个</child>
            </div>`,
  components:{
    child:{
      template:`<h1><slot></slot>子组件</h1>`
    }
  }
})
也可以是一个或多个组件
Vue.component('global1',{
  template:`<div>我是一个</div>`
})
Vue.component('global2',{
  template:`<div>没用的</div>`
})

new Vue({
  el:"#app",
  template:`<div>
               <child>
                  <global1></global1>
                  <global2></global2>
                </child>
            </div>`,
  components:{
    child:{
      template:`<h1><slot></slot>子组件</h1>`
    }
  }
})


####二、匿名插槽 上面的实例中就是匿名插槽 ,也就是这种形式 ``

####三、具名插槽(分为vue2.6.0版本前和vue2.6.0版本后)两个版本 -----------------*#####2.6.0前版本*----------------- ######第一种写法 ``` new Vue({ el:"#app", template:`
`, components:{ child:{ template:`

子组件

` } } }) ``` ######第二种写法 ``` new Vue({ el:"#app", template:`

2.6.0版本前具名插槽的第二种写法

`, components:{ child:{ template:`

子组件

` } } }) ```
-----------------*#####2.6.0后版本*----------------- ######第一种写法 ``` new Vue({ el:"#app", template:`
`, components:{ child:{ template:`

子组件

` } } }) ``` ######第二种写法 ``` new Vue({ el:"#app", template:`
`, components:{ child:{ template:`

子组件

` } } }) ```

####四、作用域插槽(分为vue2.6.0版本前和vue2.6.0版本后)两个版本 -----------------*#####2.6.0前版本*----------------- ``` new Vue({ el:"#app", template:`
`, components:{ child:{ template:`

子组件

`, data(){ return { slotProps:'2.6.0版本前作用域插槽' } } } } }) ``` -----------------*#####2.6.0后版本*----------------- ######没有名字的作用域插槽 ``` new Vue({ el:"#app", template:`
`, components:{ child:{ template:`

子组件

`, data(){ return { slotProps:'2.6.0版本后没有名字的作用域插槽' } } } } }) ``` ######有名字的作用域插槽 ``` new Vue({ el:"#app", template:`
`, components:{ child:{ template:`

子组件

`, data(){ return { slotProps:'2.6.0版本后有名字的作用域插槽' } } } } }) ``` ######一些作用域插槽的写法 ``` new Vue({ el:"#app", template:`
//匿名作用域插槽(1) //具名作用域插槽(2) //简写具名作用域插槽(3)
`, components:{ child:{ template:`

//匿名作用域插槽(1) 子组件 //具名作用域插槽(2) 子组件 //简写具名作用域插槽(3) 子组件

`, data(){ return { slotProps:'2.6.0版本后有名字的作用域插槽' } } } } }) ```
posted @ 2019-07-21 19:21  江初  阅读(243)  评论(0编辑  收藏  举报