【发布时间】:2018-01-03 20:47:54
【问题描述】:
我正在 vue 中构建一个 TabbedDetailView 可重用组件。这个想法是tab-detail 组件接收具有标题和组件的对象列表。然后它会执行逻辑,以便在您单击选项卡时显示组件。问题是这个组件有一个user_id 的道具。如何将此道具从模板外部(直接在脚本中)插入到组件中?
例如(使用带有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>
这个想法是,这可以通过只传递一个带有标题和组件的 props 对象来重用。例如。 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 }}不是有效的模板。它必须包含在一个元素中。 -
@BertEvans 我解决了这个问题。但这不是我要解决的主要问题。
-
也许你可以拼凑一个小例子来展示这个问题,让你更容易理解你想要完成的事情。
-
@BertEvans 我详细阐述了这个例子。很难将它放在 JSFiddle 中的具体示例中,因为它都是 webpack 构建的一部分。
标签: vue.js vuejs2 vue-component