2017-07-27 56 views
0

我在vue中構建了一個TabbedDetailView可重用組件。這個想法是,tab-detail組件接收一個包含標題和組件的對象列表。然後執行該邏輯,以便在單擊選項卡時顯示該組件。問題是這個組件的道具是user_id。如何將此道具從模板外部插入組件(直接在腳本中)? 例如(使用單個文件VUE部件與webpack):如何在單個文件vue組件(vue-loader中的依賴注入)初始化時將道具傳遞給vue組件?


TabDetail.vue

<template> 
<div> 
<nav class="tabs-nav"> 
    <ul class="tabs-list"> 
    <li class="tabs-item" v-for='tab in tabs'> 
     <a v-bind:class="{active: tab.isActive, disabled: !tab.enabled}" @click="switchTab(tab)">{{tab.title}}</a> 
    </li> 
    </ul> 
</nav> 

<div v-for='tab in tabs'> 
    <component :is="tab.detail" v-if='tab.isActive'></component> 
</div> 

</div> 
</template> 

<script> 
    export default { 
    name: 'NavigationTabs', 
    props: ['tabs'], 
    created: function() { 
     this.clearActive(); 
     this.$set(this.tabs[0], 'isActive', true); 
    }, 
    methods: { 
     clearActive: function() { 
     for (let tab of this.tabs) { 
      this.$set(tab, 'isActive', false); 
     } 
     }, switchTab: function(tab) { 
     if (tab.enabled) { 
      this.clearActive(); 
      tab.isActive = true; 
     } 
     }, 
    }, 
    }; 
</script> 

的想法是,這可以通過只傳遞一個道具有標題和部件對象被重新使用。例如。 tabs = [{title: 'Example1', component: Component1}{title: 'Example2', component: Component2}]我希望能夠在通過它們之前使用道具來實例化這些組件。例如。 tabs = [{title: 'Example1', component: Component1({user_id: 5})}{title: 'Example2({user_id: 10})', component: Component2}])。


SomeComponent.vue

import Vue from 'vue'; 
import TabDetail from '@/components/TabDetail' 
import Component1 from '@/components/Component1'; 
const Componenet1Constructor = Vue.extend(Component1); 

export default { 
    data() { 
    return { 
     tabs: [ 
      {title: 'Componenent 1', detail: new Component1Constructor({propsData: {user_id: this.user_id}})} 
      {title: 'Component 2', detail: Component2}, 
      {title: 'Component 3', detail: Component3}, 
     ], 
    }; 
    }, props: ['user_id'], 
    components: {'tab-detail': TabbedDetail}, 
} 
<template> 
    <div> 
    <tab-detail :tabs='tabs'></tab-detail> 
    </div> 
</template> 

Component1.vue

export default { 
    props: ['user_id'], 
}; 
<template> 
<div> 
{{ user_id }} 
</div> 
</template> 

上述方法提出了德錯誤: [Vue warn]: Failed to mount component: template or render function not defined.

我認爲這是一個好主意,因爲我試圖按照組件的依賴注入設計模式。沒有使用全局狀態,是否有更好的方法解決這個問題?

+3

'{{user_id}}'不是有效的模板。它必須包含在一個元素中。 – Bert

+0

@BertEvans我修正了這個問題。但這不是我想要解決的主要問題。 – mauzepeda

+0

也許你可以把一個小例子展示出來,這個例子可以讓你更容易理解你想要完成的事情。 – Bert

回答

0

這可以通過Inject Loader完成時使用vue加載器與單個文件vue組件,但它增加了很多不必要的複雜性,它主要用於測試。似乎管理狀態的首選方式是使用全球國有管理商店,如Vuex