2017-07-27 6 views
0

私はvueにTabbedDetailView再利用コンポーネントを構築しています。考え方は、tab-detailコンポーネントがタイトルとコンポーネントを持つオブジェクトのリストを受け取るということです。次に、タブをクリックするとコンポーネントが表示されるようにロジックを実行します。問題は、このコンポーネントにはuser_idの小道具が付いていることです。この小道具をテンプレートの外から(スクリプトの中に直接)コンポーネントに挿入するにはどうすればよいですか?例えば (webpackで単一ファイルVUEコンポーネントを使用):単一ファイル構成要素(vue-loaderの依存性注入)内の初期化時に、vue構成要素にpropsを渡す方法はありますか?


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

これは、単一ファイルのvueコンポーネントでvueローダーを使用する場合、Inject Loaderによって実行できますが、多くの不必要な複雑さが増します。これは主にテスト用です。 Vuexのようなグローバルな状態管理ストアを使うことによって、状態を管理するのが好ましい方法のようです。

関連する問題