将渲染函数传递给Vue3中的插槽

huangapple go评论61阅读模式
英文:

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:

&lt;TopBar v-slot=&quot;{ spacer }&quot;&gt;
  Some content goes here...
  &lt;spacer/&gt;
  Some more content there...
&lt;/TopBar&gt;

But it didn't work. The spacer tag renders as &lt;spacer/&gt;. Any way to accomplish this?

英文:

I have a component TopBar

&lt;script setup lang=&quot;ts&quot;&gt;
import { h } from &#39;vue&#39;;

const props = withDefaults(defineProps&lt;{ height?: number }&gt;(), { height: 50 });

const spacer = () =&gt; h(&#39;span&#39;, { class: &#39;bar__spacer&#39; } );
&lt;/script&gt;

&lt;template&gt;
  &lt;div class=&quot;bar&quot; :style=&quot;{ &#39;--height&#39;: props.height }&quot;&gt;
    &lt;slot :spacer=&quot;spacer&quot;&gt;&lt;/slot&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;style scoped lang=&quot;scss&quot;&gt;
.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);

  &amp;__spacer {
    flex-grow: 1;
  }
}
&lt;/style&gt;

When I'm using it, I want to add spacer as HTML element. So it'll look like this:

    &lt;TopBar v-slot=&quot;{ spacer }&quot;&gt;
      Some content goes here...
      &lt;spacer/&gt;
      Some more content there...
    &lt;/TopBar&gt;

But it didn't work. The spacer tag renders as &lt;spacer/&gt;. Any way to accomplish this?

答案1

得分: 1

你可以使用&lt;component :is=&quot;&quot;&gt;语法,即

&lt;TopBar v-slot=&quot;{ spacer }&quot;&gt;
  &lt;component :is=&quot;spacer&quot;/&gt;
&lt;/TopBar&gt;

Playground

英文:

You can use the &lt;component :is=&quot;&quot;&gt; syntax, i.e.

&lt;TopBar v-slot=&quot;{ spacer }&quot;&gt;
  &lt;component :is=&quot;spacer&quot;/&gt;
&lt;/TopBar&gt;

Playground

huangapple
  • 本文由 发表于 2023年4月19日 15:05:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76051614.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定