vue组件核心概念--插槽slot
1.概念
在vue中通过slot可以向子组件中指定位置插入内容
2.分类
1)普通插槽:为父组件传递数据/元素/组件给子组件,而子组件定义 <slot> 接收
(1)单个插槽/默认插槽/匿名插槽
//旧版语法: //父组件 <p slot>旧版语法</p> //子组件 <slot></slot> //新版语法: //父组件 <template v-slot> <p>新版语法</p> </template> //子组件 <slot></slot>
(2)具名插槽
//旧版语法: //父组件 <p slot="user">旧版语法</p> //子组件 <slot name="user"></slot> //新版语法: //父组件 <template v-slot:user> <p>新版语法</p> </template> //子组件 <slot name="user"></slot>
2)作用域插槽:为子组件 <slot> 绑定属性,传递数据给父组件,父组件通过 v-slot:xxx="props" 接收子组件传递的属性
// 旧版语法 // 父组件 <p slot="user" slot-scope="props">{{ props.data}}</p> // 子组件 <slot name="user" :data="name" /> export default { data() { return { name: "旧版语法" } } } // 新版语法 // 父组件 <template v-slot:user="props"> <p>{{ props.data}}</p> </template> // 子组件 <slot name="user" :data="name" /> export default { data() { return { name: "新版语法" } } }
3.注意事项
1)子组件中只能由一个默认插槽,子组件中如要有多个插槽,则加上name属性,变为具名插槽
2)如果子组件中的某一部分的数据,每个父组件都会有自己的一套对该数据的不同的呈现方式,这时就需要用到作用域插槽

浙公网安备 33010602011771号