我在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.
我认为这是一个好主意,因为我试图按照组件的依赖注入设计模式。没有使用全局状态,是否有更好的方法解决这个问题?
'{{user_id}}'不是有效的模板。它必须包含在一个元素中。 – Bert
@BertEvans我修正了这个问题。但这不是我想要解决的主要问题。 – mauzepeda
也许你可以把一个小例子展示出来,这个例子可以让你更容易理解你想要完成的事情。 – Bert