How to pass an object as props with vue router?

tzortzik picture tzortzik · May 24, 2018 · Viewed 23.4k times · Source

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:
  }
});

As you can see first I am passing to CreateComponent the user just when I initialize the route.

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.

How can I pass the otherProp and still keep the user?

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.

Answer

Jacob Goh picture Jacob Goh · May 24, 2018

It can work by using props's Function mode and params

demo: https://jsfiddle.net/jacobgoh101/mo57f0ny/1/

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"
        }
    }
})