如何使用vue路由器将对象作为道具传递? [英] How to pass an object as props with vue router?
问题描述
我有以下小提琴 https://jsfiddle.net/91vLms06/1/ >
I have the following fiddle https://jsfiddle.net/91vLms06/1/
const CreateComponent = Vue.component('create', {
props: ['user', 'otherProp'],
template: '<div>User data: {{user}}; other prop: {{otherProp}}</div>'
});
const ListComponent = Vue.component('List', {
template: '<div>Listing</div>'
});
const app = new Vue({
el: '#app',
router: new VueRouter(),
created: function () {
const self = this;
// ajax request returning the user
const userData = {'name': 'username'}
self.$router.addRoutes([
{ path: '/create', name: 'create', component: CreateComponent, props: { user: userData }},
{ path: '/list', name: 'list', component: ListComponent },
{ path: '*', redirect: '/list'}
]);
self.$router.push({name: 'create'}); // ok result: User data: { "name": "username" }; other prop:
self.$router.push({name: 'list'}); // ok result: Listing
// first attempt
self.$router.push({name: 'create', props: {otherProp: {"a":"b"}}}) // not ok result: User data: { "name": "username" }; other prop:
self.$router.push({name: 'list'}); // ok result: Listing
// second attempt
self.$router.push({name: 'create', params: {otherProp: {"a":"b"}}}) //not ok result: User data: { "name": "username" }; other prop:
}
});
如您所见,刚开始初始化路由时,我正在传递给CreateComponent
user
.
As you can see first I am passing to CreateComponent
the user
just when I initialize the route.
稍后,我需要传递另一个属性otherProp
并仍然保留user
参数.当我尝试执行此操作时,我发送的对象不会传递给组件.
Later I need to pass another property otherProp
and still keep the user
parameter. When I try to do this the object I send is not passed to the component.
如何通过otherProp
并仍然保留user
?
otherProp
的真正目的是用表单中的数据填充表单.在清单部分中,有一个对象,当我单击编辑"按钮时,我想用清单中的数据填充表单.
The real purpose of the otherProp
is to fill a form with the data from it. In the listing part I have the object and when I click the "edit" button I want to populate the form with the data that comes from the listing.
推荐答案
可以使用演示: https://jsfiddle.net/jacobgoh101/mo57f0ny/1/
添加路线时,请使用道具的功能模式,默认属性user
,它将添加route.params
作为道具.
when adding routes, use props's Function mode so that it has a default property user
and it will add route.params
as props.
{
path: '/create',
name: 'create',
component: CreateComponent,
props: (route) => ({
user: userData,
...route.params
})
}
推送中传递的参数会自动添加到道具中.
params passed in push will automatically be added to props.
self.$router.push({
name: 'create',
params: {
otherProp: {
"a": "b"
}
}
})
这篇关于如何使用vue路由器将对象作为道具传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!