[Vuejs]-Referencing router-link params data in vuejs

2👍

You can set the props property to true on the article route as described in Passing Props to Router Component section.

{
  name: 'article'
  path: '/viewArticle/:id',
  component: ArticleView // whatever you named the component
  props: true
}

Then you your ArticleView component you can add an id prop:

<script>
  export default {
    name: 'article',
    props: ['id'],
    data() {
      return {
      }
    }
  }
</script>

The id is now available to you directly on the component and you can fetch the article.

If you want to you can also preload the article so that the actual article is passed instead of the id.

You do that by adding beforeRouteEnter to the component:

 <script>
  export default {
    name: 'article',
    props: ['id'],
    data() {
      return {
        article: null,
      }
    },
    beforeRouteEnter (to, from, next) {
       // your ajax stuff goes here
       // I use axios in this example
       axios.get(`/api/article/${to.params.id}`)
         .then((article) => {
           next(vm => {
             vm.article = article
           })
         })
         .catch(() => {
            next('/404')
         })
    }
  }
</script>

So before the router is entered it will fetch the article. This has the added advantage that all your component code can assume that you have the article loaded already. You don’t have to deal with the case where it is loaded or not loaded.

In addition you can also access the matched route like this: this.$route and the router for navigation like this: this.$router (with r at the end).

Leave a comment