gpt4 book ai didi

javascript - Vue : components inside component

转载 作者:行者123 更新时间:2023-12-03 00:17:35 28 4
gpt4 key购买 nike

通过少量渲染来构建嵌套组件系统的好方法是什么?请参阅下面带有主要问题(“如何...”)的所需代码:

tab.vue(子组件)

<template>
<slot></slot>
</template>

<script>
export default {
name: 'Tab',
props: ['title']
}
</script>

tabs.vue(容器组件)

<template>
<div class="tabs-switchers">
<b
v-for="(o, i) in items"
:key="`tab-button-${i}`"
>
{{ o.componentInstance.props.title }}
</b>
</div>
<div class="tabs-contents">
<div class="tabs-contents-item"
v-for="(o, i) in items"
:key="`tab-item-${i}`"
>
<!-- HOW TO RENDER TAB CONTENT HERE??? -->
</div>
</div>
</template>
<script>
export default {
name: 'Tabs',
computed () {
items () {
return this.$slots.default
}
}
}
</script>

page.vue(带有使用示例的组件)

<template>
<tabs>
<tab title="tab 1"><p>Tab #1 content</p></tab>
<tab title="tab 2"><p>Tab #2 content</p></tab>
<tab title="tab 3"><p>Tab #3 content</p></tab>
</tabs>
</template>

最佳答案

解决方案的关键是使用组件的渲染函数( https://v2.vuejs.org/v2/guide/render-function.html )来实现一些定制。示例:

export default {
name: 'Tabs',
render: function (createElement) {
const buttons = []
const tabs = []
const children = this.$slots.default // shortcut

for (let i = 0; i < children.length; i++) {
buttons.push(createElement(
'button',
children[i].componentOptions.propsData.title
))
tabs.push(createElement(
'div',
{
class: i === 0 ? 'active tab' : 'tab',
attrs: {
id: `tab-${i}`
}
},
children[i].componentOptions.children
))
}
const buttonsContainer = createElement('div', { class: 'buttons' }, buttons)
const tabsContainer = createElement('div', tabs)

const root = createElement('div', { class: 'tabs' }, [buttonsContainer, tabsContainer])
return root
}
}

我不确定 VNode API(children[i].componentOptions.propsData.title - 这是正确的方法吗?),但它有效,而且这是解决问题的正确方法,我确定。

干杯!

关于javascript - Vue : components inside component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54475900/

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