我有一个组件Portfolio.vue
,它有一个子组件Category.vue
,可以通过<router-link :to = "{ name: 'category', params: { id: id }}">
得到。 Category.vue
从路由器接收参数id
。
在Category.vue
中,我要导入许多组件之一。例如,如果id
来自Category.vue
='google'的Portfolio.vue
,那么我有id = 'google'
,并且我想在{{ 1}}并在那里渲染。
这是我的google.vue
代码段
Category.vue
这是我的Portfolio.vue
<template>
<div class = "categories">
<div
class = "category"
v-for = "(category, index) in categories"
:key = "index"
>
<div class = "category-title">{{category.name}}</div>
<div class = "category-description">{{category.description}}</div>
<div class = "category-portfolios">
<div
class = "category-portfolio"
v-for = "(portfolio, index) in category.portfolios"
:key = "index"
>
<router-link :to = "{ name: 'category', params: { slug: portfolio.slug }}">
{{portfolio.slug}}
</router-link>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "portfolio",
data() {
return {
pageName: 'Portfolio',
categories: []
}
},
mounted() {
fetch('api/portfolio/index')
.then(response => response.json())
.then(json => this.categories = Object.assign({}, json.categories))
.catch(error => {
console.log(error);
})
}
}
</script>
<style lang = "scss" scoped>
</style>
还有我的Category.vue
组件
<template>
<div>
{{slug}}
<component
:is="currentTabComponent"
class="test"
></component> <!--this component should be rendered-->
</div>
</template>
<script>
// import this.$route.params.slug from './components/portfolios/this.$route.params.slug'
//this code is wrong, but the main idea is to import component
export default {
name: "category",
data() {
return {
slug: ''
}
},
beforeCreate() {
this.slug = this.$route.params.slug;
},
computed: {
// maybe here I should definded what component should I render. This was in example in Vue documentation
currentTabComponent: function () {
return this.slug
}
},
}
</script>
<style scoped>
</style>
我阅读了Load component/template depending on the route param vuejs,并观看了https://jsfiddle.net/wostex/yLu0uza8/2/和https://vuejs.org/v2/guide/components.html#Dynamic-Components,但是仍然无法从文件夹/文件中导入特定的google.vue
组件,如何在父组件(<template>
<div>
<h1>This is google portfolio</h1>
</div>
</template>
<script>
export default {
name: "google"
}
</script>
<style scoped>
</style>
)中声明此特定.vue
组件,最后如何在父组件(.vue
)中呈现此特定Category.vue
组件{{1 }}。
主要问题是如何从路由器数量中按路由器参数导入特定组件? 谢谢。
答案 0 :(得分:0)
您能否仅使组件本身根据路由ID动态更改其内容?
答案 1 :(得分:0)
您可以使用dynamic components并将id
参数as props传递到您的路线。
像这样:
const Category = Vue.component('category', {
name: 'category',
template: '#category',
props: ['id']
});
const router = new VueRouter({
routes: [
{ path: '/category/:id', name: 'category', component: Category, props: true },
]
})
和在模板中:
<template id="category">
<div>
<h3>Category : {{ id }}</h3>
<component :is="id"></component>
</div>
</template>