【发布时间】:2017-08-08 10:39:14
【问题描述】:
我正在使用 VueJS 2.0 和 vue-router 2,并尝试显示基于路由参数的模板。我正在使用一个视图 (WidgetView) 并更改该视图中显示的组件。最初我显示一个小部件列表组件(WidgetComponent),然后当用户在 WidgetView 的 WidgetComponent 中选择一个小部件或新按钮时,我想将 WidgetComponent 换出并显示 WidgetDetails 组件,并将信息传递给该组件:
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>
路由器.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>
但我不知道如何将 id 从 WidgetView 中的脚本(不是模板)代码传递给给定的模板。
【问题讨论】:
标签: javascript vue.js vuejs2 vue-router