javascript 如何通过一个对象作为 prop 与vue路由器?

t1qtbnec  于 2023-02-02  发布在  Java
关注(0)|答案(3)|浏览(80)

我有一把小提琴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的真实的目的是用它的数据填充表单,在列表部分我有一个对象,当我点击“编辑”按钮时,我想用列表中的数据填充表单。

pu3pd22g

pu3pd22g1#

它可以使用props's Function modeparams工作
Vue 2演示:https://jsfiddle.net/hacg6ody/
添加路由时,使用props's Function mode,使其具有默认属性user,并且它将添加route.params作为 prop 。

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

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

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

mccptt672#

下面是我使用路由器发送对象的简单解决方案。

this.$router.push({
 name: 'someName'
 params: {
  obj: {...someObject}
 },
});

如果你想在下一页使用obj,你可以在下面得到数据。

this.$route.params.obj
4nkexdtk

4nkexdtk3#

我在Vue Router 4和Vue 3以及Composition API中使用以下设置:
1.在路由器中,按如下方式定义路由:

{
  name: 'someroute',
  path: 'someroute?id=:id&name=:name`,
  component: [YourComponentNameHere],
  props: true,
}

1.在发送器组件中:

router.push('someroute',
  params: {
    id: 1,
    name: 'John'
  }
})

1.在接收器组件中,使用以下命令访问它们:

router.currentRoute.value.params.id
router.currentRoute.value.params.name

相关问题