vue2.0 插槽

使用场景

如开发一个组件,里面一些子元素希望是有调用着来定义,可以使用slot

一:没有slot
没有插槽slot我不展示
Vue.component('child',{
    template:`
child
` })

结果:无插槽.png

注释:在父组件中调用子组件时给子组件添加插槽内容,如果子组件里不包含元素,则添加的插槽内容会被抛弃

二:默认插槽

我是默认插槽
{{parentMsg}}
Vue.component('child1',{
    template:`
child1哈哈哈哈
` })

结果:默认插槽.png

注释:

  1. 没有设置子组件插槽内容,则会显示子组件中的内容
  2. 设置了子组件插槽内容,则插槽内容会替代中的内容
  3. 子组件插槽内容是在父组件调用时设置,默认的作用域是父组件,因此可以访问父组件的值,这点个人认为类似父组件给子组件传值props,但是props主要传递值,插槽可以传递DOM
三:具名插槽
 
    
    
    
    

Vue.component('child2',{
    template:`
child2
` })
四:作用域插槽

    
    

Vue.component('child3',{
    template:`
child3
`, data(){ return{ msg:"子组件的参数" } } })

结果:scope.png

 
    
    

 Vue.component('child4',{
    template:`
child4
`, data(){ return{ childMsg:[ { name:"张三", age:18 }, { name:"李四", age:19 } ] } } })

结果:scope1.png
注释:
作用域插槽与普通插槽区别:[作用域插槽]父组件插槽的内容能访问子组件传的数据[普通插槽]则不行

源码地址: https://github.com/shangliaoy...

你可能感兴趣的:(vux)