Vue.js VueJS:多个路由的一个组件

Vue.js VueJS:多个路由的一个组件,vue.js,vue-component,vue-router,Vue.js,Vue Component,Vue Router,我是VueJS世界的新手 我的应用程序使用vue路由器处理路由更改。这是它的配置方式: new Router({ routes: [{ path: "/", component: Articles }, { path: "/articles/:category", component: Articles }] }); 如您所见,我有两条路由由同一个组件处理。这个想法很简单。当我们在主页上时,显示任何类别的文章。当我们在分类页面上时,显示该分类的文章

我是VueJS世界的新手

我的应用程序使用
vue路由器
处理路由更改。这是它的配置方式:

new Router({
  routes: [{
    path: "/",
    component: Articles
  }, {
    path: "/articles/:category",
    component: Articles
  }]
});
如您所见,我有两条路由由同一个组件处理。这个想法很简单。当我们在主页上时,显示任何类别的文章。当我们在分类页面上时,显示该分类的文章

问题是,组件如何检测路由是否已更改(例如从主页更改为类别页)

我提供了以下解决方案:

function loadArticles() {};

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

但我认为,这是一个糟糕的解决方案。

以下是我在我的一个小项目上所做的,我使用模板来显示一篇文章

这是我的路由器

   '/post/:id': {
    name: 'post',
    component: require('./components/article.vue')
},
在我的
.vue
文件中,我获取
$route.params
以获取文章的
id
,然后将其显示在我的
ready
函数中

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

您需要获取
类别
参数,然后根据该参数呈现模板

它应该是这样的:

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

建议使用“监视”。

为什么监视$route对象不是个好主意?在Vue路由器文档中,当您想在路由激活后获取数据时,建议使用这种方法。