【问题标题】:How to pass an object as props with vue router?如何使用 vue 路由器将对象作为道具传递?
【发布时间】:2018-11-03 12:16:45
【问题描述】:

我有以下小提琴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 的真正目的是用其中的数据填写表格。在列表部分我有对象,当我单击“编辑”按钮时,我想用列表中的数据填充表单。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-router


    【解决方案1】:

    使用props's Function modeparams可以工作

    演示:https://jsfiddle.net/jacobgoh101/mo57f0ny/1/

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

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

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

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

    【讨论】:

    【解决方案2】:

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

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

    如果你想在下一页使用 obj。您可以在下面获取数据。

    this.$route.params.obj
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 2019-09-04
      • 2018-02-12
      • 1970-01-01
      • 2022-01-26
      • 2021-09-11
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多