简体   繁体   中英

How to pass props between routes in vue.js?

I want to send a variable as a prop from a route to another in vue.

I have a vue component, Champions, using a v-for and creating a new component called ChampionCard for each character in a JSON file, and binding the current champion each time.

In ChampionCard, I just show the name and image of the champion. I want that, when clicking on a ChampionCard, you get redirected to another component called Champion with URL champions/:champion.

But I can't find a way to send the champion data between those 2 routes.

The Champions component :

<div class="champions">
    <ChampionCard v-bind:champion="champion" v-for="champion in champions" :key="champion.key"> 

    </ChampionCard>
 </div>

The ChampionCard component :

<article @click="redirectTo(champion)" class="champion">
      <img class="champion-icon" :src="champion.image" :alt="champion.name">
      <h2 class="champion-name"> {{ champion.name }} </h2>
</article>
redirectTo(champion) {
      this.$router.push({ name: 'champion', params: { champion: champion.key }})
    }

The above code is working as I get redirected to champions/championName, but I don't have access to my champion variable. What would be the best way to send it as a prop in Champion component ?

Thanks :)

My alternative is: While redirecting to champions/:champion route, just send the id of the champion (such as champions/123 ).

When you are redirecting to this route, you can store champion object in a global place (say store ). So that you can lookup with id (123) when you're mounting the route.
One step further, if you cannot find the object in the global store, you can initiate a remote call. So that your route will not be broken if 123 is not in the store. (User can go directly to that route if they save some bookmarks of that page etc.)

To keep your object in the global place, you have different alternatives:

  1. Simple State Management (Simple/Basic implementation)
  2. Using Vuex

I think you can achieve what you want doing something like this:
Declare a new route:

{
  path: '/champion/:championKey',
  name: 'Some name',
  component: ChampionComponent,
}

Then, when redirecting to this new route:

redirectTo(champion) {
  this.$router.push("/champion/" + champion.key)
}

Now you can access to the url param like this:

this.$route.params.championKey // as declared in router.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM