Home > OS >  Cannot make Vue route with param to work with component
Cannot make Vue route with param to work with component

Time:10-26

My own list of ideas, why route with parameter is simply not recognized by Vue and gives me redirect to "/home" component is over. Other simple routes work fine.

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;

Request for http://localhost:8080/product/1 gives me redirect to Home.

I suspect this code is not enough for troubleshooting, so is there any idea how i can debug routing? There must be $router.params somewhere, but i cannot figure where to catch it's value during runtime or where to set a breakpoint. Thank you.

CodePudding user response:

You can use beforeEnter hook for debugging. Refer this link for more router guards.

CodePudding user response:

You probably need to pass the :id parameter to the component using the route props config:

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

props: true, passes current named parameters as props with the same name. In this case, it assues you have a prop 'id' in ProductDetails to read from.

Another way is to read the route param inside the component:

$route.params.id

Other alternatives can be found here: https://router.vuejs.org/guide/essentials/passing-props.html

  • Related