我正在使用VueJS 2.0和vue-router 2,我正在尝试根据路由参数显示模板。我正在使用一个视图(WidgetView)并更改该视图中显示的组件。最初我展示了一个小部件列表组件(WidgetComponent),然后当用户在WidgetView的WidgetComponent中选择一个小部件或新按钮时,我想要交换WidgetComponent并显示WidgetDetails组件,并将信息传递给该组件: / p>
WidgetComponent.vue:
<template>
...
<router-link :to="{ path: '/widget_view', params: { widgetId: 'new' } }"><a> New Widget</a></router-link>
<router-link :to="{ path: '/widget_view', params: { widgetId: widget.id } }"><span>{{widget.name}}</span></router-link>
</template>
<script>
export default {
name: 'WidgetComponent',
data() {
return {
widgets: [{ id: 1,
name: 'widgetX',
type: 'catcher'
}]}
}
}
</script>
WidgetView.vue
<template>
<component :is="activeComponent"></component>
</template>
<script>
import WidgetComponent from './components/WidgetComponent'
import WidgetDetail from './components/WidgetDetail'
export default {
name: 'WidgetView',
components: {
WidgetComponent,
WidgetDetail
},
mounted: function () {
const widgetId = this.$route.params.widgetId
if (widgetId === 'new') {
// I want to pass the id to this component but don't know how
this.activeComponent = 'widget-detail'
}
else if (widgetId > 0) {
// I want to pass the id to this component but don't know how
this.activeComponent = 'widget-detail'
}
},
watch: {
'$route': function () {
if (this.$route.params.widgetId === 'new') {
// how to pass id to this compent?
this.activeComponent = 'widget-detail'
}
else if (this.$route.params.widgetId > 0){
// how to pass id to this compent?
this.activeComponent = 'widget-detail'
}
else {
this.activeComponent = 'widget-component'
}
}
},
data () {
return {
activeComponent: 'widget-component',
widgetId: 0
}
}
}
</script>
WidgetDetail.vue
<template>
<option v-for="manufacturer in manufacturers" >
{{ manufacturer.name }}
</option>
</template>
<script>
export default {
props: ['sourcesId'],
...etc...
}
</script>
router.js
Vue.use(Router)
export default new Router({
routes: [
{
path: '/widget_view',
component: WidgetView,
subRoutes: {
path: '/new',
component: WidgetDetail
}
},
{
path: '/widget_view/:widgetId',
component: WidgetView
},
]
})
我无法使路线参数工作但我设法通过硬编码路线来使路线工作,即
<router-link :to="{ path: '/widget_view/'+ 'new' }"> New Widget</router-link>
但我不知道如何从WidgetView中的脚本(而非模板)代码将id传递给给定的模板。
答案 0 :(得分:1)
这是一个基本示例http://jsfiddle.net/ognc78e7/1/。尝试使用router-view
元素保存您的组件。此外,在组件内部使用props来传递URL中的变量。文档解释得更好http://router.vuejs.org/en/essentials/passing-props.html
//routes
{ path: '/foo/:id', component: Bar, props:true }
//component
const Bar = { template: '<div>The id is {{id}}</div>',props:['id'] }
不确定您希望采用哪种方式,但您可以让/foo/
路径实际上是创建小部件,然后拥有动态/foo/:id
路径。或者你可以像我在这里做的那样,foo路径就像一个链接到不同东西的起始页面。