gpt4 book ai didi

vue.js - 如何在 Vue3 中渲染多个插槽?

转载 作者:行者123 更新时间:2023-12-02 19:02:54 25 4
gpt4 key购买 nike

如何使用 h() 函数在 Vue3 setup() 函数中渲染以下模板?

<label v-for="service in services" :key="service">
<slot name="before" :service="service"></slot>
foobar
<slot name="after" :service="service"></slot>
</label>

最佳答案

h() arguments是:

// @returns {VNode}
h(
// {String | Object | Function } tag
// An HTML tag name, a component or an async component.
// Using function returning null would render a comment.
//
// Required.
'div',

// {Object} props
// An object corresponding to the attributes, props and events
// we would use in a template.
//
// Optional.
{},

// {String | Array | Object} children
// Children VNodes, built using `h()`,
// or using strings to get 'text VNodes' or
// an object with slots.
//
// Optional.
[
'Some text comes first.',
h('h1', 'A headline'),
h(MyComponent, {
someProp: 'foobar'
})
]
)

组件的 setup() arguments在下面。 setup() 也可以 return a render function (从 h() 返回一个 VNode 的函数):

setup(
// {Object} Component prop values
props,

// {Object} Contains `attrs`, `emit`, and `slots`
context
)

上下文的 slots 属性包含每个给定槽的函数。这些函数接收作为 props 传递给插槽的参数,每个函数返回相应槽的VNode。例如,要获取 before 插槽的 VNode 并传递 service 的插槽属性,调用 context.slots.before({ service : 'myService' }).

因此,您的模板的等效渲染函数将类似于以下内容:

import { h } from 'vue'

export default {
props: {
services: {
type: Array,
default: () => [],
},
},
setup({ services }, { slots }) {
return () =>
services.map((service) =>
h( //
'label', //
{ // <label :key="service">
key: service, //
}, //
[
slots.before({ service }), // <slot name="before" :service="service" />
'foobar', // foobar
slots.after({ service }) // <slot name="after" :service="service" />
]
) // </label>
)
},
}

demo

关于vue.js - 如何在 Vue3 中渲染多个插槽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65355291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com