slot插槽
踩坑:在vue中,自定义的组件标签名称、slot的name属性、一些变量,多个英文单词之间尽量采用-连接,不要使用_或者驼峰命名
解释:在子组件中,可以在任意位置使用标签进行占位,在父组件中使用该子组件时,就可以直接将数据传递到子组件中,并放入占位处。
<div id = "vueli3">
<div><!--父组件-->
<p>slot的使用</p>
<child-el1> <!--通过不同的slot的名字来将数据插入子组件中不同的位置,v-slot:和#的作用是一样的,#缩写,方便开发-->
<template v-slot:sa>{{name}}</template>
<template #sb>{{2334}}</template>
</child-el1>
<div>
<!--调用子组件的标签后,直接在标签内使用双花括号,就能将数据传入到子组件slot占位处-->
<child-el2>{{124}}</child-el2>
</div>
</div>
</div>
const app2 = Vue.createApp({
data(){
return{
name: "linuy"
}
}
})
//子组件1:(有两个slot标签占位,为了父组件能准确的将数据插入对应的占位处,应给每个slot标签一个name属性)
app2.component("childEl1",{
template:"<slot name='sa'></slot>\
<h2>\
<slot name='sb'></slot>\
</h2>"
})
//子组件2:
app2.component("childEl2",{
template:"<h1>\
<slot></slot>\
</h1>"
})
app2.mount("#vueli3")
插槽slot+props用法:
<div id = "vueli3"> <course v-for="course in courses"> <template v-slot:slota> <category :category="course.category"></category> </template> <template v-slot:slotb> <course-name v-for="name in course.courseNames" :courseName="name"></course-name> </template> </course> </div>
const app2 = Vue.createApp({ data(){ return{ courses:[ {category: "编程语言",courseNames:["golang","python","java ee"]}, {category: "技术框架",courseNames:["element UI","SpringMvc","SpringBoot"]}, {category: "编译工具",courseNames:["IDEA","vscode","notepad++"]} ] } } }) app2.component("course",{ template:`<div> <slot name="slota"></slot> <ul> <slot name="slotb"></slot> </ul> </div>` }) app2.component("category",{ props: ["category"], template:"<h3>{{category}}</h3>" }) app2.component("course-name",{ props: ["coursename"], template:"<li>{{coursename}}</li>" }) app2.mount("#vueli3")