Vues-如何在渲染功能中使用v-for和作用域插槽

时间:2020-09-07 16:05:25

标签: vue.js vue-component vue-router vuejs3

我有一个呈现导航链接的组件。它基于scopedSlots功能。该组件工作正常,但我想对其进行改进。这是目前的用法:

<horizontal-navigation :items="items" #default="{ item }">
  <navigation-item :item="item"></navigation-item>
</horizontal-navigation>

items的数组如下:

[
  { path: '/about', title: 'About' },
  { path: '/', title: 'Home' }
]

以下是 Horizo​​ntalNavigation 组件模板:

<template>
    <div class="horizontal-navigation">
      <slot v-for="(item, index) in items" :key="index" :item="item"></slot>
    </div>
</template> -->

这是 NavigationItem 组件模板

<template>
    <router-link class="navigation-item" :path="item.path">{{ item.title }}</router-link>
</template>

我试图用render函数替换 Horizo​​ntalNavigation 组件的模板,因为我想使该组件在没有提供广告位内容的情况下以默认样式呈现链接。 / p>

在这里我被困住了:

  render () {
    const options = {
      class: 'horizontal-navigation'
    }
    let children = []
    if (this.$slots.default) {
      children = this.$slots.default({ items: this.items }) // NEED TO ITERATE ITEMS TO CREATE INSTANCES OF A COMPONENT PASSED TO DEFAULT SLOT
    }
    return h('div', options, children)
  }

我在文档中找到的最接近的东西是:

render() {
  if (this.items.length) {
    return Vue.h('ul', this.items.map((item) => {
      return Vue.h('li', item.name)
    }))
  } else {
    return Vue.h('p', 'No items found.')
  }
}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

在模板中,尝试使用条件渲染来渲染slot或后备内容:

 <div class="horizontal-navigation">
   <template  v-for="(item, index) in items" >
       <template v-if="$slots.default">
           <slot  :item="item"></slot>
       </template>
       <template v-else>
          <router-link class="navigation-item" :path="item.path">{{ item.title }}</router-link>
       </template>         
   </template>
</div>