1

I have a question about vue-router. How could I accomplish a route / routes like this:

example.com/blog/category/value/tags/value/page/value 

Category, tags and page should be optional.

So if I visit example.com/blog/category/value/page/value - it should load the same component.

I'm using vue 2.

Thanks!

2
  • you are looking for dynamic matching check this docs Commented Oct 2, 2016 at 21:18
  • yes, I checked the docs, I also checked the examples on github, but they don't really answer my question. Could you give me an example or point me in to the right direction? Commented Oct 2, 2016 at 22:52

1 Answer 1

2

try this

const Blog = {
  template: `<div>Blog 
    <h3>{{  $route.params.category }}  {{  $route.params.page }}</h3>
  </div>`
};

const router = new VueRouter({
  routes: [
    { path: '/blog(/category/)?:category([^\/]+)?(/page/)?:page?', component: Blog }
  ]
});

const app = new Vue({ router }).$mount('#app');

html:

<div id="app">
    <p>
       <router-link to="/blog">blog</router-link>
       <router-link to="/blog/category/cat1/page/page1">/blog/link1</router-link>
       <router-link to="/blog/category/cat2/page/page2">/blog/link2</router-link>
    </p>
      <router-view></router-view>
</div>

Vue-router

Sign up to request clarification or add additional context in comments.

5 Comments

Hmm, seems to be working for the most part. The only issues I see with this is that when you go to a route for example: example.com/blog/category/test the :category value gets split, only getting the first character of the value for example test will be 't', and the rest is assigned to a :page value, which will be 'est'. But if you would go example.com/blog/page/test than it works fine.
@PauliusKrutkis try my new answer
Yes, now it works as expected, thanks! There is one more problem I have, but I guess it's beyond the scope of this question. It's difficult referencing this route in the code. Right now this: <router-link to="/blog/category/cat1/page/page1">/blog/link1</router-link> will work just fine, but I need to do more complicated logic behind this structure, I was hoping I could reference this route by name like this <router-link :to="{ name: 'blog', params: { category_value: 'test', page_value: 2 }}">link</router-link> but what happens is that the result becomes this: /blogtest2 :/ , but thanks anyway!
@PauliusKrutkis did you eventually find a solution for the last problem about linking to named routes?
I did not, maybe this was a bad solution for the thing I wanted to build, I've instead built my own custom router for this. On the other hand if I used query string structure than this would have worked, but I think that 'pretty' URL structure would be better for SEO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.