Skip to content
Advertisement

How do I set a route in hash mode with params with Vue Router 3 (Vue 2)

Currently, my Vue router is using hash mode for my router and I am looking for a way to pass parameters when generating links to another component. so far I came up with this:

this is what it currently looks like in my Markup:

<b-button variant="primary" class="rounded-0" :href="'/article/' + article.id" >View post</b-button>

I am passing down the article id into the link so that when the user clicks on the button, it will direct him to a component where the article with the respective id is visible with its content.

the problem comes when setting up routes, below is my index.js under router

import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '@/views/Main.vue'


Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'Main',
    component: Main
  },

  {
    path: '/menu',
    name: 'Menu',
    component: ()=> import('../views/Menu.vue')
  },

  {
    path:'/cart',
    name:'Cart',
    component: () => import('../views/Purchase.vue')
  },

  {
    path:'/blog',
    name:'Blog',
    component: () => import('../views/Blog.vue')
  },
  {
    path:'/article/:id',
    component: ()=> import('../views/ArticlePage.vue')
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes
})

export default router

As you can see for the /article/:id path I am trying to link it with the ArticlePageComponent. The problem is that /article/:id doesn’t seem to work for hash modes, it will just redirect me to the homepage. Any suggestions?

Advertisement

Answer

Instead of having href in b-button why don’t have a handler in methods like

routePage(article) {
  this.$router.push({
   path: `/article/${article.id}`
  });
}

and trigger it on click event

<b-button variant="primary" class="rounded-0" @click="routePage(article)" >View post</b-button>

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement