0

I'm trying to make an edit button for an object(song). I want to pass my data to the edit form, so the input it will be completed with the actual data, but I always get undefined. I tried a lot of solutions but no one worked for me. What's the problem?

My Song Component, I am trying to pass its data to the edit form

<template>
  <div class="hello">
    <h1>{{ song.name }}</h1>
    <p>Author: {{ song.author }}</p>
    <p>Views: {{ song.views }}</p>
    <!-- <button @click="$router.push('/update-song?id=' + song.id )">Update</button> -->
    <button @click="$router.push({path: '/update-song', Component: UpdateSong, props: {song: song}})">Update</button>
  </div>
</template>

<script>
export default {
  name: 'Song',
  props: {
    song: Object
  }
}
</script>

My edit view:

<template>
    <div>
        <p>Update a song: {{this.author}} - {{this.name}}</p>
        <input type="text" id="name" placeholder="Name" v-model="name"/><br/>
        <input type="text" id="author" placeholder="Author" v-model="author"/><br/>
        <input type="text" id="country" placeholder="Country" v-model="country"/><br/>
        <input type="text" id="duration" placeholder="Duration" v-model="duration"/><br/>
        <input type="text" id="views" placeholder="Views" v-model="views"/><br/>
        <input type="text" id="genre" placeholder="Genre" v-model="genre"/><br/>
        <button @click="updateSong">Update Song</button>
    </div>
</template>

<script>
export default{
    name: 'UpdateSong',
    props: {
        song: Object
    },
    mounted() { 
         console.log(this.song) //undefined
     },
    data(){
        return{
            name: '',
            author: '',
            country: '',
            duration: 0,
            views: 0,
            genre: ''
        }
    },
    methods: {
        updateSong(){...}
    }
}
</script>

My routes:

const routes = [...,
    {
        path: '/update-song',
        name: "updateSong",
        component: UpdateSong
    }
]
  • 1
    I'd use a `push` with some `query params` [like this](https://router.vuejs.org/guide/essentials/navigation.html#navigate-to-a-different-location). Or use a store for such a purpose (like Vuex or Pinia). In your code, you're expecting some props like if they are tied to the `UpdateSong` component but they are more on the router part I guess. You could pass those props directly to your component too I suppose but I'd stick to the 2 first solutions. Maybe check [that one](https://router.vuejs.org/guide/essentials/passing-props.html#object-mode) too. Inspect the Vue devtools too, may be useful! – kissu Dec 18 '22 at 14:11
  • 1
    Does this answer your question? [Pass an object as param to router.push (vue-router@4.05)](https://stackoverflow.com/questions/66864658/pass-an-object-as-param-to-router-push-vue-router4-05) – Neha Soni Dec 18 '22 at 15:05

0 Answers0