Suppose I have a Vue.js component like this:
var Bar = Vue.extend({ props: ['my-props'], template: '<p>This is bar!</p>' });
And I want to use it when some route in vue-router is matched like this:
router.map({ '/bar': { component: Bar } });
Normally in order to pass 'myProps' to the component I would do something like this:
Vue.component('my-bar', Bar);
and in the html:
<my-bar my-props="hello!"></my-bar>
In this case, the router is drawing automatically the component in the router-view element when the route is matched.
My question is, in this case, how can I pass the the props to the component?
Conclusion. To pass props to Vue. js components instantiated by Vue Router, we can pass the prop value to router-view .
You can pass strings, arrays, numbers, and objects as props. But can you pass a function as a prop? While you can pass a function as a prop, this is almost always a bad idea. Instead, there is probably a feature of Vue that is designed exactly to solve your problem.
<router-view :some-value-to-pass="localValue"></router-view>
and in your components just add prop:
props: { someValueToPass: String },
vue-router will match prop in component
sadly non of the prev solutions actually answers the question so here is a one from quora
basically the part that docs doesn't explain well is
When props is set to true, the
route.params
will be set as the component props.
so what you actually need when sending the prop through the route is to assign it to the params
key ex
this.$router.push({ name: 'Home', params: { theme: 'dark' } })
so the full example would be
// component const User = { props: ['test'], template: '<div>User {{ test }}</div>' } // router new VueRouter({ routes: [ { path: '/user', component: User, name: 'user', props: true } ] }) // usage this.$router.push({ name: 'user', params: { test: 'hello there' // or anything you want } })
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