<!DOCTYPE html><html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Vue插槽</title><script src="vue.js"></script></head><body><div class="app"><child><!-- 在使用子组件时(插槽也可以)可以直接使用父组件的数据 --><div slot="one"><h1>{{name}}</h1></div><!-- 子组件重定义插槽内容时可以使用子组件数据,需要子组件插槽定义时:帮数据绑定到插槽的自定义属性上;在调用子组件插槽时,通过slot-scope属性来获取插槽对象,通过插槽对象上的定义的属性获取子组件数据 --><div slot="two" slot-scope="slot"><ol><li v-for="n of slot.data">{{n}}</li></ol></div></child><child></child></div><template id="child"><div><slot name="one"><h1>插槽自定义内容</h1></slot><slot name="two" :data="arr"><ul><li v-for="n of arr">{{n}}</li></ul></slot></div></template></body><script type="text/javascript">let child={// props:["name"],template:"#child",data(){return {arr:[1,2,3,4,5,6],}}}const vm=new Vue({data:{name:"ldy",},el:".app",components:{child,}});</script></html>

1.在创建组件时,可以通过<slot></slot>标签创建插槽,插槽中可以填入默认数据信息;插槽可以通过name属性定义插槽的名字(具名插槽定义)。
2.在调用组件时,组件中自定义的标签内容,自动填充到组件插槽中的文职,如果没有自定义内容,则显示插槽中的默认数据信息;,在调用时通过自定义标签的slot属性来关联插槽(具名插槽的使用)
3.在调用组件时,插槽中自定义的html标签可以使用父组件中的数据
4.使用子组件时,插槽中自定义内容,可以使用子组件数据
5.插槽作用域:
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号