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.
Another way to access the router props is to add an import statement at the top of the component and import 'withRouter'. import { withRouter } from 'react-router-dom'; Then in the export default statement at the end of the component you would wrap the component in 'withRouter'. export default withRouter(HomePage);
Using props in Vue After you have set up the props, you can then use it inside your component as though the data was defined inside the same component. This means you can set up method calls and easily access this.
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" } } })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With