【问题标题】:Cannot make Vue route with param to work with component无法使用参数使 Vue 路由与组件一起使用
【发布时间】:2021-10-25 20:26:31
【问题描述】:

我自己的想法列表,为什么 Vue 根本无法识别带有参数的路由并让我重定向到“/home”组件已经结束。其他简单的路线也可以。

routes.js:

import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Login from "../components/login/Login.vue";
import Profile from "../components/profile/Profile.vue";
import ProductDetails from "../components/product/ProductDetails.vue";

import { partner_routes } from "../views/partner/routes";
import { purchase_routes } from "../views/purchase/routes";


import ProductCatalog from "@/views/product-catalog/ProductCatalog.vue";


const product_routes = [
  {
    path: "/product-catalog",
    name: "product-catalog",
    component: ProductCatalog,
  },
];



const routes = [

  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: '/product/:id',
    name: "ProductDetails",
    component: ProductDetails,
    // meta: {
    //   requiresAuth: true,
    // },
   },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/profile",
    name: "Profile",
    component: Profile,
    // meta: {
    //   requiresAuth: true,
    // },
  },

];

const router = new VueRouter({
  routes, // short for `routes: routes`
});
export default router;

对 http://localhost:8080/product/1 的请求让我重定向到主页。

我怀疑这段代码不足以进行故障排除,那么我知道如何调试路由吗?某处必须有 $router.params ,但我不知道在运行时在哪里捕获它的值或在哪里设置断点。 谢谢。

【问题讨论】:

  • ../components/product/ProductDetails.vue 中有什么内容?

标签: vue.js vue-router


【解决方案1】:

您可以使用beforeEnter 挂钩进行调试。更多路由器保护请参考link

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
  • 嗨,纳伦。不,它不起作用。看起来我有问题的死记硬背甚至没有解决。
  • 你的其他路线还好吗?
【解决方案2】:

您可能需要使用路由props 配置将:id 参数传递给组件:

{
path: '/product/:id',
name: "ProductDetails",
component: ProductDetails,
props: true
}

props: true,将当前命名参数作为具有相同名称的 props 传递。在这种情况下,它假设您在 ProductDetails 中有一个 prop 'id' 可供读取。

另一种方法是读取组件内部的路由参数:

$route.params.id

可以在此处找到其他替代方案: https://router.vuejs.org/guide/essentials/passing-props.html

【讨论】:

  • 嗨,伊戈尔。不,它不起作用。看起来我有问题的死记硬背甚至没有解决。
【解决方案3】:

最后,我得到了它的工作。我已将“模式:历史”添加到“const router = new VueRouter(...)”,现在正在解析新路由。我仍然不知道为什么新路由(甚至没有参数化,因为它后来证明)不能在哈希模式下工作,而像“/profile”这样的旧路由工作正常。 我测试过的网址不包含哈希“#”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-15
    • 2019-02-18
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 2018-08-24
    • 2017-08-27
    相关资源
    最近更新 更多