0
votes

I am new to vue and vue router and am using Vue router in history mode. The app contains a menu which is dynamically loaded

<router-link 
  tag="li" 
  class="link"
  v-for="item in menu" 
  v-bind:key="item.id" 
  :to="item.slug" 
  :exact="item.slug === '/' ? true : false">{{ item.content }}
</router-link>

It works well as long as I stay in the parent routes like http://localhost:8080/posts As soon as I navigate a level deeper, e.g. to a post with the id 8 http://localhost:8080/posts/8 with a routerlink inside the Template

<router-link 
  tag="h2" 
  class="link" 
  :to="{ name: 'post', params: { id: post.id }}"> 
{{ post.title.rendered }} 
</router-link>  

it works in one way, but doesnt go back to the parent route when I click the main navigation links. Instead just adds the link of the main menu to the end of the route, e.g. instead of http://localhost:8080/posts

http://localhost:8080/posts/posts 

The router

const router = new Router({
  mode: 'history',
  base: '',
  routes: [
      { path: '/', name: 'home', component: HomePage },
      { path: '/posts', name: 'posts', component: PostsPage },
      { path: '/posts/:id', name: 'post', component: SinglePost },      
      { path: '/projects', name: 'projects', component: ProjectsPage },
      { path: '/projects/:id', name: 'project', component: ProjectPage },
      { path: '/:page', name: 'page', component: SinglePage },
      { path: "*", redirect: '/' },
   ],
  // etc..
  });

I guess I am making a common mistake, but I can´t find a solution. Any help appreciated.

1
What does your menu looks like in v-for="item in menu" ?Al-un
Is your item.slug 'posts' or '/posts'?dziraf
The item.slug is just 'posts'Carsten H
@Al-un the for loop creates just the menu entries according for the length of the menu arrayCarsten H

1 Answers

0
votes

You can use absolute paths. Instead of

<router-link 
 tag="h2" 
 class="link" 
 :to="{ name: 'post', params: { id: post.id }}"> 
 {{ post.title.rendered }} 
</router-link> 

use

<router-link 
 tag="h2" 
 class="link" 
 :to="{ name: '/post', params: { id: post.id }}"> 
  {{ post.title.rendered }} 
</router-link> 

The change is /post vs post in router-link's :to attribute.

You could and probably should use nested routes and components for posts posts/:id, but this a little more work and you my not need it at the moment. More on nested routes here.