首页 > 解决方案 > 如何将参数传递给未命名的路由:TypeError:'instanceof' 的右侧不可调用

问题描述

我有一条路线:

路由器.js

       {
            path: "/books/new/:title",
            name: "new_book",
            component: () => 
import('./components/user/NewBookView.vue')
        }

我尝试通过路由器推送:

CreateBook.vue

this.$router.push({
    name: "new_book",
    params: {
         title: this.bookJson.data.title,
         book: this.bookJson.data
    }
});

但是我得到一个

Error in nextTick: "TypeError: 
Right-hand side of 'instanceof' is not callable"

错误。

我需要bookJson作为参数传递给我的NewBookView.vue组件:

新书视图.vue

...
        data:  function()  {
            return {
                book: JSON
            }
        },
        created() {
            this.book = 
this.$route.params.book;
        }
...

我试着做

this.$router.push({
    path: "/books/new/" + 
this.booksJson.data.title,
    params: {
         book: this.bookJson.data
    }
});

book参数似乎是undefined.

因此,除非路由被命名,否则我似乎无法传递参数,但如果它被命名,我也无法推送它。

编辑:我试图把它改成这个,但仍然得到Error in nextTick: "TypeError: Right-hand side of 'instanceof' is not callable"错误:

路由器.js

{
    path: "/books/new/:title",
    name: "new_book",
    component: () => import('./components/user/NewBookView.vue'),
    props: route => ({
        // set component property book to the route.params.book value
        book: route.params.book,
        ...route.params
    })
}

CreateBook.vue

this.$router.push({
    name: "new_book",
    params: {
         title: this.bookJson.data.title,
         book: this.bookJson.data
    }
});
})

新书视图.vue

export default {
    props:  {
        book: JSON
    },
    created() {
        this.props.book = this.$route.params.book;
    }
}

标签: javascriptvue.jsvue-componentvue-router

解决方案


使用道具功能模式

像这样设置你的路由器:

{
    path: "/books/new/:title",
    name: "book",
    component: () => import("../pages/Book.vue"),
    props: route => ({
        // set component property book to the route.params.book value
        book: route.params.book,
        ...route.params
    })
}

而不是 using dataprops请在您的组件上使用:

export default {
  name: "home",
  props: {
    title: String, 
    book: Object
  }
};

并像这样推送到您的路线:

this.$router.push({
    name: "book",
    params: {
        title: "Foo Bar",
        book: {
            id: 1,
            title: "Foo Bar",
            author: "John Doe"
        }
    }
});

演示:https ://codesandbox.io/s/vue-router-demo-3cfqs?file=/pages/Home.vue


推荐阅读