【发布时间】:2025-12-18 07:55:02
【问题描述】:
我有一个呈现导航链接的组件。它基于scopedSlots 功能。该组件工作正常,但我想改进它。这是它目前的使用方式:
<horizontal-navigation :items="items" #default="{ item }">
<navigation-item :item="item"></navigation-item>
</horizontal-navigation>
items 的数组如下所示:
[
{ path: '/about', title: 'About' },
{ path: '/', title: 'Home' }
]
这是 HorizontalNavigation 组件模板:
<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>
我正在尝试将 HorizontalNavigation 组件的模板替换为 render 函数,因为我想让该组件在未提供插槽内容时以默认样式呈现链接。
这就是我卡住的地方:
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.')
}
}
有什么建议吗?
【问题讨论】:
-
你在使用 vue 3 吗?
-
@BoussadjraBrahim,是的,先生
-
我可以建议使用模板语法的解决方案,可以吗?
-
@BoussadjraBrahim,请这样做,这太棒了!
标签: vue.js vue-component vue-router vuejs3