如何在单个文件vue组件内的初始化中将props传递给vue组件(vue-loader中的依赖注入)?

时间:2017-07-27 23:04:22

标签: vue.js vuejs2 vue-component

我在vue中构建了一个TabbedDetailView可重用组件。我们的想法是tab-detail组件接收具有标题和组件的对象列表。然后它执行逻辑,以便当您单击选项卡时,将显示该组件。问题是这些组件的支柱是user_id。如何从模板外部(直接在脚本中)将此prop插入到组件中? 例如(使用带有webpack的单个文件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}]我希望能够在传递它们之前用props实例化这些组件。例如。 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.

我认为这是一个好主意,因为我试图遵循依赖注入设计模式与组件。如果不使用全局状态,是否有更好的方法解决这个问题?

1 个答案:

答案 0 :(得分:0)

当使用带有单个文件vue组件的vue加载器时,这可以通过Inject Loader完成,但它增加了许多不必要的复杂性,并且它主要用于测试。管理状态的首选方式似乎是使用像Vuex这样的全局状态管理存储。

相关问题