簡體   English   中英

Vue:組件內的組件

[英]Vue: components inside component

用少量渲染構建嵌套組件系統的好方法是什么? 請參閱下面的主要問題('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>

解決方案的關鍵是使用組件的渲染功能( 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 - 這是正確的方法嗎?)但它有效並且它是解決我確定的正確方法。

干杯!

您不需要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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM