Vue:组件内部的组件

时间:2019-02-01 08:49:40

标签: javascript vue.js vuejs2

用少量的渲染构建嵌套组件系统的好方法是什么?看到下面带有主要问题('HOW TO ...')的所需代码:

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>

2 个答案:

答案 0 :(得分:0)

呈现v-for内容不需要slot

Vue.component('Tabs', {
  template: `
    <div class="tab-container">
      <slot></slot>
    </div>
  `
})

Vue.component('Tab', {
  template: `
    <div class="tab">
      <strong>{{title}}</strong>
      <slot></slot>
    </div>
  `,
  
  props: ['title']
})

new Vue().$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <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>
</div>

答案 1 :(得分:0)

解决方案的关键是使用组件的渲染功能(https://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 –正确的方法吗?),但是它可以工作,并且是解决Im sure的正确方法。

干杯!

相关问题