V-slot
缩写:#
预期:可放置在函数参数位置的 JavaScript 表达式 (在支持的环境下可使用解构)。可选,即只需要在为插槽传入 prop 的时候使用。
参数:插槽名 (可选,默认值是 default)
插槽的使用
- 声明一个插槽组件在html里面使用slot标签。
<template>
<h1>this is slotcomp start </h1>
<slot></slot>
<h1>this is slotcomp end </h1>
</template>
<script>
export default {
name: "SlotComp",
}
</script>
<style scoped>
</style>
- app组件引入该组件如下
<template>
<h1>this is app start </h1>
<SlotComp>
<h2 style="color: red">this is app slot</h2>
</SlotComp>
<h1>this is app end </h1>
</template>
<script>
import SlotComp from "./components/SlotComp";
export default {
name: 'App',
components:{
SlotComp
}
}
</script>
<!--scoped 限制局部样式-->
<style lang="scss">
</style>
- 插槽的使用很简单,直接在组件标签里面填写内容就可以展示到子组件的slot标签中,
<SlotComp>
<h2 style="color: red">this is app slot</h2>
</SlotComp>
- 效果如下
具名插槽
如果子组件多个插槽,父组件区分插槽的位置,就可以使用name属性
- 子组件添加两个插槽包含name属性
<slot></slot>
<slot name="one"></slot>
<slot name="two"></slot>
- 在父组件使用插槽的时候,v-slot:name就可以指定插槽对应的子位置
<template v-slot:one>
<h2 style="color: red">this is v-slot:one </h2>
</template>
<template #two>
<h2 style="color: red">this is v-slot:two</h2>
</template>
<template v-slot:default>
<h2 style="color: red">this is v-slot:default</h2>
</template>
参数传递
父组件使用插槽组件参数
- 在子组件中声明参数
data(){
return {
user:{name:'this is SlotComp user.name '}
}
}
- 在子组件中使用
<slot name="two" :user2="user"></slot>
:后面跟的名字是父组件获取的组件名字
- 在父组件中使用如下
<template v-slot:two="data">
<h2 style="color: red">this is v-slot:two {{ data.user2.name}}</h2>
</template>
data为插槽组件所有的参数,不是单个,所以需要使用data.user2获取user的值
完整代码
app.vue
<template>
<h1>this is app start </h1>
<SlotComp>
<template v-slot:one>
<h2 style="color: red">this is v-slot:one </h2>
</template>
<template v-slot:two="data">
<h2 style="color: red">this is v-slot:two {{ data.user2.name}}</h2>
</template>
<template v-slot:default>
<h2 style="color: red">this is v-slot:default</h2>
</template>
</SlotComp>
<h1>this is app end </h1>
</template>
<script>
import SlotComp from "./components/SlotComp";
export default {
name: 'App',
components:{
SlotComp
}
}
</script>
<!--scoped 限制局部样式-->
<style lang="scss">
</style>
SlotComp.vue
<template>
<h1>this is slotcomp start </h1>
<slot></slot>
<slot name="one"></slot>
<slot name="two" :user2="user"></slot>
<h1>this is slotcomp end </h1>
</template>
<script>
export default {
name: "SlotComp",
data(){
return {
user:{name:'this is SlotComp user.name '}
}
}
}
</script>
<style scoped>
</style>