如何setup()使用该函数在 Vue3 函数中渲染以下模板h()?
<label v-for="service in services" :key="service">
<slot name="before" :service="service"></slot>
foobar
<slot name="after" :service="service"></slot>
</label>
Run Code Online (Sandbox Code Playgroud)
论据h()是:
// @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'
})
]
)
Run Code Online (Sandbox Code Playgroud)
该组件的setup()参数如下。setup()还可以返回一个 render 函数(一个返回VNodefrom的函数h()):
setup(
// {Object} Component prop values
props,
// {Object} Contains `attrs`, `emit`, and `slots`
context
)
Run Code Online (Sandbox Code Playgroud)
上下文的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>
)
},
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5331 次 |
| 最近记录: |