Th.Gleb
Th.Gleb

Reputation: 25

VueJS: one component for many routes

I'm a newbie to the world of VueJS.

My app uses vue-router to handle with routes changing. This's how it's configured:

new Router({
  routes: [{
    path: "/",
    component: Articles
  }, {
    path: "/articles/:category",
    component: Articles
  }]
});

As you can see, I've got 2 routes handled by the same component. The idea is very simple. When we're on a home page, show articles from any category. When we're on a category page, show articles from that category.

The question is, how a component can detect whether the route's changed, e.g, from home page to category page?

I've come with this solution:

function loadArticles() {};

Vue.component("Articles", {
  mounted: loadArticles,
  watch: { "$route": loadArticles }
});

But I think, that's a bad solution.

Upvotes: 1

Views: 1004

Answers (2)

Egor Stambakio
Egor Stambakio

Reputation: 18126

It should look something like this:

watch: {
    '$route' (to, from) {
        if (this.$route.params.category) {
            this.loadArticles(category);
        } else {
            this.loadArticles();
        }
    }
}

'watch' is recommended here, in docs.

Upvotes: 1

highFlyingSmurfs
highFlyingSmurfs

Reputation: 3039

Here's what I have done on a little project of mine, I'm using the template to display single article

This is my router

   '/post/:id': {
    name: 'post',
    component: require('./components/article.vue')
},

In my .vue file, I get the $route.params to get the id of the article then displayed it in my ready function.

  $.get('api/posts/' + this.$route.params.id, function(data){
            myPost.current = data;
        })

You'll need to get the category parameter then rendered the template according to it.

Upvotes: 1

Related Questions