首页 > 解决方案 > 如何通过参数传递整个对象

问题描述

我是 vue 路由器的新手,不明白如何在页面链接中填充帖子

<router-link :to{name: "componentName"}></router-link>

我尝试使用如下对象但没有成功

<router-link :to="{name: 'componentName', params: {
  book: {
  slug: book.slug,
  title: book.title,
  ratings: book.rating,
  author: book.author,
  synopsis: book.synopsis
  }
}}">

并收到

<template>
    <div>
        <h1>{{this.$route.params.book}}</h1>
        
    </div>
</template>

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

<style lang="scss" scoped>

</style>

我做错了什么或者有更好的方法吗?

标签: vue.jsvue-router

解决方案


您可以在路线上使用道具模式,props: true在声明路线时添加:

const routes = [
  {
    name: "book",
    path: "/book",
    component: Book,
    props: true // <-- Add this
  }
];

const router = new VueRouter({
  routes,
  mode: "history"
});

new Vue({
  router,
  render: (h) => h(App)
}).$mount("#app");

并在您的Book页面上添加props

<script>

// BookPage.vue

export default {
  name: "Book",
  props: {
    book: Object, // <--- Add this
  },
};
</script>

然后简单地传递使用params你的router-link

<router-link :to="{name: 'book', params: {
  book: {
    slug: book.slug,
    title: book.title,
    ratings: book.rating,
    author: book.author,
    synopsis: book.synopsis
  }
}}">

演示:https ://codesandbox.io/s/pensive-sunset-vgoy5?file=/src/App.vue

阅读有关路由器道具的更多信息:https ://router.vuejs.org/guide/essentials/passing-props.html


推荐阅读