medve.cfg
medve.cfg

Reputation: 89

How can I pass an object in params when using $router.push()?

I want to loop through an array of objects and when I click on an item I want to display a page populated with data from the other component.

Here is my router.js

{
    path: '/artists',
    component: () => import('../views/Artists/ArtistsStart.vue'),
    children: [
      {
        path: '',
        component: () => import('../views/Artists/Artists.vue')
      },
      {
        path: ':name',
        component: () => import('../views/Artists/Artist.vue')
      }
    ]
  }

ArtistsStart.vue only has <router-view> and a transition animation so I don't think it's important

Artists.vue

<template>
    <div v-for="(artist, index) in artists" :key="index" @click="artistLink(artist)">
        {{artist.name}}
    </div>
</template>

<script>
    export default {
        data() {
            return {
                artists: [{
                        name: 'artist 1',
                        route: 'artist1',
                        text: 'lorem ipsum',
                        imageUrl: ''
                    },
                    {
                        name: 'artist 2',
                        route: 'artist2',
                        text: 'lorem ipsum',
                        imageUrl: ''
                    }
                ]
            }
        },
        methods: {
            artistLink(artist) {
                this.$router.push(`/artists/${artist.route}`);
            }
        }
    }
</script>

I didn't use <router-link> because I don't want to pass the text and other data through the URL

Artist.vue

<template>
    <div>
        <div>
            {{name}}
        </div>
        <div>
            {{text}}
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
            name: this.$route.params.name,
            text: this.$route.params.text
            }
        }
    }
</script>

I can only display the artist name in the Artist.vue page.

Upvotes: 0

Views: 312

Answers (1)

lenglei
lenglei

Reputation: 1248

router.push and router-link are meant to do the same thing which is to redirect you to a new location/address, for example, /artists/1 (they are just doing it in a different way, dynamically vs statically). So in principle, it is the responsibility of that component to find the related data for this address, not the requester. In your case, it is the responsibility of the Artist.vue to find the data with the given artist Id, or artist route. In reality, you should have some method in this component to either fetch data from a local data store, e.g. using a vuex store or just plain js (put the artist list into a artist.js and reuse that in both Artists.vue, Artist.vue), or from a server using ajax.

Upvotes: 1

Related Questions