首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Vue3中渲染多个插槽?

如何在Vue3中渲染多个插槽?
EN

Stack Overflow用户
提问于 2020-12-18 18:22:27
回答 1查看 1.7K关注 0票数 1

例如,如何使用h函数在vue3的setup函数中呈现以下模板?

代码语言:javascript
复制
<label v-for="service in services" :key="service">
  <slot name="before" :service="service"></slot>
  foobar
  <slot name="after" :service="service"></slot>
</label>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-19 22:18:30

这些h() arguments是:

代码语言:javascript
复制
// @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的函数):

代码语言:javascript
复制
setup(
  // {Object} Component prop values
  props,

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

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

因此,您的模板的等效呈现函数将如下所示:

代码语言:javascript
复制
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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65355291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档