vue.js - Vue Router 使用 router-link 在两个组件之间传递数据

标签 vue.js vue-component vue-router vue-props

我正在开发一个 SPA 网站,我正在尝试使用路由器链接在两个组件之间传递一些数据。

基本上我有一个“专辑”组件(这里称为宝丽来),它的“数据”中包含所有专辑歌曲的歌词。然后我有一个歌曲组件(此处称为 Canzone),我想根据单击的歌曲动态传递每首歌曲的歌词。

这是我的代码:

routes.js

import Polaroid from './components/albums/Polaroid'
import Canzone from './components/songs/Canzone.vue'

export default {

    mode: 'history',
    linkActiveClass: 'font-bold',

    routes: [

        {
            path: '/polaroid',
            component: Polaroid
        },

        {
            path: '/polaroid/:canzone',
            name: 'polaroid',
            component: Canzone
        },
    ]
};

Polaroid.vue(这是我显示歌曲列表的专辑组件)

<template>
<div>
  <ul class="leading-7">
    <li v-for="canzone in this.canzoni" :key="canzone.nome" >
      <router-link :to="{ name: 'polaroid', params: { name: canzone.path } }"> {{ canzone.nome }} </router-link>
    </li>
  </ul>
</div>
</template>

<script>
    export default {
         data(){
             return {
                canzoni: [            // all the songs
                    {
                    nome: 'Song1',
                    path: 'song-1',
                    numero: 1,
                    testo: 'lyrics1'
                    },
                    {
                    nome: 'Song2',
                    path: 'song2',
                    numero: 2,
                    testo: 'lyrics2'
                    },
                    {
                    nome: 'Song3',
                    path: 'song3',
                    numero: 3,
                    testo: 'lyrics3'
                    },
                ],


            };
        },
    }
</script>

Canzone.vue(这是歌曲组件,我想在其中动态地显示歌曲歌词)

<template>
<div>
     
    LYRICS HERE

    {{ $route.params.canzone }}      // not working

</div>
</template>

<script>
    export default {
        
    }
</script>

如何通过路由器链路传递数据?谢谢!

谢谢!

最佳答案

您应该在 Polaroid.vueparams 中使用 canzone 而不是 name

  <router-link :to="{ name: 'polaroid', params: { canzone: canzone.path } }"> {{ canzone.nome }} </router-link>

关于vue.js - Vue Router 使用 router-link 在两个组件之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63112048/

相关文章:

javascript - 在 Nuxt 3 API 和中间件中使用 cookie

javascript - 自定义指令进行组件渲染

typescript - 带有 Typescript : missing RouteConfig 的 Vue3 路由器

vue.js - vue-router 应该在点击时路由,不工作

javascript - Vue.js 路由器不显示正确的子路由

javascript - 如何显示/隐藏动态数组中的 v-for 元素?

vue.js - 未调用 Vue prop 验证

node.js - npm run dev会重复相同的过程,并且不会启动应用程序

vue.js - 我如何着手在 vue.js 中创建一个始终大写的输入?