我有一把小提琴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:
}
});
正如您首先看到的,我在初始化路由时将user
传递给CreateComponent
。
稍后我需要传递另一个属性otherProp
,并且仍然保留user
参数。当我尝试这样做时,我发送的对象没有传递到组件。
我怎样才能通过otherProp
而仍然保留user
?otherProp
的真实的目的是用它的数据填充表单,在列表部分我有一个对象,当我点击“编辑”按钮时,我想用列表中的数据填充表单。
3条答案
按热度按时间pu3pd22g1#
它可以使用props's Function mode和
params
工作Vue 2演示:https://jsfiddle.net/hacg6ody/
添加路由时,使用props's Function mode,使其具有默认属性
user
,并且它将添加route.params
作为 prop 。push中传入的参数会自动添加到props中。
mccptt672#
下面是我使用路由器发送对象的简单解决方案。
如果你想在下一页使用obj,你可以在下面得到数据。
4nkexdtk3#
我在Vue Router 4和Vue 3以及Composition API中使用以下设置:
1.在路由器中,按如下方式定义路由:
1.在发送器组件中:
1.在接收器组件中,使用以下命令访问它们: