【发布时间】:2019-01-10 14:06:54
【问题描述】:
我有一个组件Portfolio.vue,它有一个子组件Category.vue,我可以通过<router-link :to = "{ name: 'category', params: { id: id }}"> 获得。 Category.vue 从路由器接收参数id。
在Category.vue 我想导入许多组件之一。例如,如果id 即Category.vue 来自Portfolio.vue = 'google',那么我有id = 'google',我想在Category.vue 中导入组件google.vue 并在那里渲染它。
这是我的Portfolio.vuesn-p
<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>
还有我的google.vue 组件
<template>
<div>
<h1>This is google portfolio</h1>
</div>
</template>
<script>
export default {
name: "google"
}
</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,但我仍然不知道如何从文件夹/文件中导入特定的.vue组件,我如何声明这个特定的@987654343 @ 父组件中的组件 (Category.vue) 以及最后如何在父组件中呈现这个特定的 .vue 组件 (Category.vue) <template></template>。
所以主要问题是如何通过路由器参数从组件数量中导入特定组件? 谢谢。
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component vue-router