v-slot插槽实践用法讲解

1,498 阅读1分钟

当声明的子组件需要在某个位置留出一段空间,让调用子组件的父组件自己扩展维护时,就需要用到vue的插槽概念 v-solt。 v-solt分为三种类型: 1.匿名插槽(也叫默认插槽),不需要命名,并且每个子组件有且只能声明一个

eg.

//父组件
<component> 
    <template v-slot:default>
       任意内容
    </template>
</component> 

//子组件 component
<slot>默认值</slot>

声明方式就是子组件写个不带name属性的 slot元素,父组件调用也不需要指定name,默认内容填充到匿名插槽中,v-slot:default声明的模块可以省略,默认子组件标签内的未指定name的都填充到匿名组件中。 2.具名插槽,与匿名插槽的区别是,子组件声明时,需要定义name属性,父组件调用时也需要指定插槽对应的子组件插槽的name属性

eg.

//父组件
<component> 
    <template v-slot:cos> // 指定包裹内容是填充到子组件name为cos的插槽内
       任意内容
    </template>
</component> 

//子组件
<slot name="cos">默认值</slot> // 需要定义name属性

3.作用域插槽,可以从父组件中拿到子组件中定义的数据

eg.

// 子组件
<slot name="cos" :data="content">
    {{ content.data}}
 </slot> 
data() {
    return {
      content:{
        data:"测试数据"
        ...
      }
    }
  },
  ...
  }
//父组件
<component>
 <template v-slot:cos="dataFromChild" >//dataFromChild 自定义接收子组件的数据的对象
   {{dataFromChild.content.data}}
 </template> 
</component> 

这样就可以在父组件中拿到子组件的数据进行操作了。