1

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.

1
  • Why would watching the $route object be a bad idea ? It's recommended way in Vue Router Docs, when you want to fetch data after route is activated. Commented Apr 1, 2017 at 17:06

2 Answers 2

1

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.

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.