1、怎么把具名插槽中子组件的值传递给父组件
代码如下
//父组件
<header-slot :level="2222">
//#content 等价于v-slot:content
<template #content="scope">
//父组件接受到子组件中的scope.data
<div v-for="(item, index) in scope.data" :key="index">{{ item }}</div>
</template>
<template #footer="scope">
<div v-for="(item, index) in scope.data" :key="index">{{ item }}</div>
</template>
</header-slot>
import HeaderSlot from './components/HeaderSlot'
components: {
HeaderSlot,
},
//子组件
HeaderSlot.ts
import { h, } from "vue"
export default {
props: {
level: {
type: Number,
required: true,
}
},
setup(props: any, context: any) {
// 返回render函数
const handleClick = () => {
console.log("我点击了", props.level)
}
return () => h(
'div',
{
onClick: () => {
handleClick()
}
},
//暴露给父组件一个data数据
[context.slots.content({
data: ["小明", "小哥", "小五"]
}),
h('span', {
onClickStop: (event: any) => {
event.stopPropagation()
}
}, "我是中间插槽"),
context.slots.footer({
data: ["张三", "李四", "王五"]
}
)]
)
}
}
2、
//父组件
<render-node :title="title"></render-node>
import RenderNode from './components/RenderNode'
components: {
RenderNode,
},
//子组件中
import Vue, { h, resolveComponent } from "vue"
//是组件
import ElButton from './Button.vue'
//RenderNode.ts
//要为某个组件创建一个 VNode,传递给 h 的第一个参数应该是组件本身。
export default {
props: {
title: {
type: String,
default: "33333",
}
},
setup(props: any, context: any) {
return () => h(ElButton, {
title: '484848',
style: {
color: 'red',
fontSize: '14px'
},
},
{
//默认插槽
default: (props: any, content: any) => {
return h('span', null, "我是默认的的插槽")
},
//footer的插槽
footer: (props: any) => h('span', null, "我是footer的插槽"),
}
)
}
}
//ElButton
<template>
<div>
<slot title="默认标题"></slot>
<slot name="footer" title="footer标题"></slot>
</div>
</template>
<script lang="ts">
import Vue, { defineComponent } from 'vue'
export default defineComponent({})
</script>
<style lang="sass" scoped>
</style>