【问题标题】:VueJS: one component for many routesVueJS:多个路由的一个组件
【发布时间】:2017-08-26 19:34:12
【问题描述】:

我是 VueJS 世界的新手。

我的应用使用vue-router 来处理路线变化。这是它的配置方式:

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

如您所见,我有 2 条路由由同一个组件处理。这个想法很简单。当我们在主页上时,显示任何类别的文章。当我们在一个类别页面上时,显示该类别的文章。

问题是,组件如何检测路由是否发生变化,例如从主页到分类页面?

我有这个解决方案:

function loadArticles() {};

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

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

【问题讨论】:

  • 为什么观看 $route 对象是个坏主意? Vue Router Docs 中推荐的方式,当你想在路由激活后获取数据时。

标签: vue.js vue-component vue-router


【解决方案1】:

这是我在我的一个小项目中所做的,我正在使用模板显示单篇文章

这是我的路由器

   '/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;
        })

您需要获取category 参数,然后根据它渲染模板。

【讨论】:

    【解决方案2】:

    它应该看起来像这样:

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

    'watch'推荐here, in docs

    【讨论】:

      猜你喜欢
      • 2019-10-14
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 2018-07-23
      相关资源
      最近更新 更多