Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing props to Vue.js components instantiated by Vue-router

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?

like image 842
Robert Avatar asked Jun 21 '16 06:06

Robert


People also ask

Can you pass props through a router view?

Conclusion. To pass props to Vue. js components instantiated by Vue Router, we can pass the prop value to router-view .

Can you pass functions as props in Vue?

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.


2 Answers

<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

like image 79
lukpep Avatar answered Oct 30 '22 06:10

lukpep


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     } })  
like image 44
ctf0 Avatar answered Oct 30 '22 05:10

ctf0