gpt4 book ai didi

javascript - 如何使用 vue 路由器将对象作为 Prop 传递?

转载 作者:可可西里 更新时间:2023-11-01 02:06:08 24 4
gpt4 key购买 nike

我有以下 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:
}
});

正如您首先看到的,我在初始化路由时将 user 传递给了 CreateComponent

稍后我需要传递另一个属性 otherProp 并仍然保留 user 参数。当我尝试这样做时,我发送的对象没有传递给组件。

如何传递 otherProp 并仍然保留 user

otherProp 的真正目的是用其中的数据填充表单。在列表部分,我有对象,当我单击“编辑”按钮时,我想用来自列表的数据填充表单。

最佳答案

它可以通过使用 props's Function mode 来工作和参数

Vue 2 演示:https://jsfiddle.net/hacg6ody/

添加路由时,使用props's Function mode这样它就有一个默认属性 user 并且它会添加 route.params 作为属性。

{
path: '/create',
name: 'create',
component: CreateComponent,
props: (route) => ({
user: userData,
...route.params
})
}

push 中传入的参数会自动添加到 props 中。

self.$router.push({
name: 'create',
params: {
otherProp: {
"a": "b"
}
}
})

关于javascript - 如何使用 vue 路由器将对象作为 Prop 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com