Elena
Elena

Reputation: 13

Vuejs: data through the router-view

Is it a good practice to pass data through the router-view? I have a nested router and some children have to have access to the data that parent is having. I know Vuex is the way to pass the data all over the app, but I`d like to know what are the exact disadvantages of binding data to the router-view to make it available in the child components. So for now I have something like that:

<router-view v-bind:list="array" />

Upvotes: 1

Views: 3212

Answers (2)

Tony Tom
Tony Tom

Reputation: 1583

You can programtically pass through router like below from parent component trigger below fn on click or redirection

this.$router.push({
      name: 'ChildRouteName',
      params: {'type':'name', 'id': '1',}
})

and in child component receive the parameters like this

type = this.$route.params['type']
id = this.$route.params['id']

Upvotes: 2

Radu Diță
Radu Diță

Reputation: 14171

You can pass data to the rendered component using the router-view but most likely is not what you want.

Routing can happen from any part of your app, but if you pass info via router-view you need to update the data that is bound to the view, which in turn means to have access to the component enclosing the template that presents router-view. This ends up tightly coupling components or using the bus/vuex.

You could use Vuex to pass the information, but there is a much easier way to pass information when routing.

You can define your route to transform parameters set when routing to props to the component. More info here. This means that you can make a call similar to this:

<router-link :to="{ name: 'routeName', params: { id: 1 }}">Go to route</router-link>

and then whatever component is registered for routeName will get the prop id set to value 1. The same will happen if you trigger a navigation programatically.

Upvotes: 0

Related Questions