英文:
Pass render function to slot in Vue3
问题
I have a component TopBar
<script setup lang="ts">
import { h } from 'vue'
const props = withDefaults(defineProps<{ height?: number }>(), { height: 50 })
const spacer = () => h('span', { class: 'bar__spacer' } )
</script>
<template>
<div class="bar" :style="{ '--height': props.height }">
<slot :spacer="spacer"></slot>
</div>
</template>
<style scoped lang="scss">
.bar {
position: relative;
display: flex;
flex: 0 0 calc(var(--height) * 1px);
width: 100%;
align-items: center;
padding: 0 10px;
background-color: var(--bg-top-bar);
border-bottom: 1px solid var(--bg-separator);
&__spacer {
flex-grow: 1;
}
}
</style>
When I'm using it, I want to add spacer
as an HTML element. So it'll look like this:
<TopBar v-slot="{ spacer }">
Some content goes here...
<spacer/>
Some more content there...
</TopBar>
But it didn't work. The spacer tag renders as <spacer/>
. Any way to accomplish this?
英文:
I have a component TopBar
<script setup lang="ts">
import { h } from 'vue';
const props = withDefaults(defineProps<{ height?: number }>(), { height: 50 });
const spacer = () => h('span', { class: 'bar__spacer' } );
</script>
<template>
<div class="bar" :style="{ '--height': props.height }">
<slot :spacer="spacer"></slot>
</div>
</template>
<style scoped lang="scss">
.bar {
position: relative;
display: flex;
flex: 0 0 calc(var(--height) * 1px);
width: 100%;
align-items: center;
padding: 0 10px;
background-color: var(--bg-top-bar);
border-bottom: 1px solid var(--bg-separator);
&__spacer {
flex-grow: 1;
}
}
</style>
When I'm using it, I want to add spacer
as HTML element. So it'll look like this:
<TopBar v-slot="{ spacer }">
Some content goes here...
<spacer/>
Some more content there...
</TopBar>
But it didn't work. The spacer tag renders as <spacer/>
. Any way to accomplish this?
答案1
得分: 1
你可以使用<component :is="">
语法,即
<TopBar v-slot="{ spacer }">
<component :is="spacer"/>
</TopBar>
英文:
You can use the <component :is="">
syntax, i.e.
<TopBar v-slot="{ spacer }">
<component :is="spacer"/>
</TopBar>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论