[英]How to pass props to a vue component at initialization inside single file vue components (dependency injection in vue-loader)?
我正在vue中构建TabbedDetailView可重用组件。 这个想法是, tab-detail
组件接收具有标题和组件的对象列表。 然后执行逻辑,以便在单击选项卡时显示组件。 问题在于该组件的prop是user_id
。 如何从模板外部(直接在脚本中)将此道具插入组件中? 例如(将单个文件vue组件与webpack一起使用 ):
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}]
我希望能够在传递道具之前用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.
我认为这是一个好主意,因为我正在尝试对组件进行依赖注入设计模式。 有没有使用全局状态的更好的方法来解决此问题?
当使用具有单个文件vue组件的vue loader时,可以通过Inject Loader来完成,但这会增加很多不必要的复杂性,并且主要用于测试。 看来,管理状态的首选方法是使用全局状态管理存储(如Vuex) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.