v-slot
限制:
- v-slot 只允许添加在
<template>
标签中 - (有一种例外情况);只有默认插槽时(v-slot:default),组件标签可以被当作插槽的模板来使用。vue文档----详情
编译作用域:
父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。
默认插槽
父组件:<templaye> <p>abc</p> </templaye>
子组件:<templaye> <slot></slot> </templaye>
插槽默认值
插槽可以使用默认值<slot>default</slot>
,若父组件不提供任何模板,将渲染为默认值default,如果提供模板,那会把default替换掉
具名插槽:
v-slot:header(简写#header)
(Vue2.6.11版本前的写法:slot="slotProps")
Parent
<template v-slot:header>
<p>NameSlot</p>
</template>
child
<template>
<slot name="header"></slot>
</template>
作用域插槽
<!- -接收 prop 的具名插槽- ->
v-slot:header="slotProps"(简写:#header="slotProps")
(Vue2.6.11版本前的写法:slot-scop="slotProps")
<child-component>
<template #headers="slotProps">
//1、所有子组件插槽传过来的数据(:headers="layout")都会被当成一个数据对象(键值:headers)存放到slotProps对象中
2、引用:slotProps.headers.header
<p>{{slotProps.headers.header}}</p>
</template>
</child-component>
子组件
Vue.component('child',{
data () {
return {
layout: {
header: '作用域插槽'
}
}
},
template:
`<div>
<slot name="headers" :headers="layout"></slot> <!-- 默认插槽,作用域插槽 -->
</div>`
})
常用场景:
父组件(不同或单个)对子组件处理后的数据有不同的操作,渲染方式,这时就需要用到作用域插槽。
封装组件(如:列表)
1.父组件传递数据给子组件
2.子组件处理应用数据
3.子组件通过 <slot name="child-one" :todo="todo">
的方式,把新数据传递给父组件
4.父组件通过v-slot:child-one="slotProps"
的方式,接受todo对象,之后通过slotProps.todo.xxx
的方式使
有时候使用封装的组件后,需要拿到封装的组件渲染后的数据进行更多的逻辑操作