Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use custom router or symlinks to avoid code duplication #3

Open
Kasheftin opened this issue Apr 22, 2020 · 1 comment
Open

Use custom router or symlinks to avoid code duplication #3

Kasheftin opened this issue Apr 22, 2020 · 1 comment

Comments

@Kasheftin
Copy link

That's a very interesting and useful article and the code!
I noticed that the pages/index.vue, pages/top.vue, and pages/t/_tag.vue use pretty much the same code. It's possible to use the route name or path to determine what has to be shown and avoid code duplication. There're several simple ways to refactor this:

  1. Move the pages/index.vue content to components/ArticleList.vue (and get an advantage of the new fetch approach being used in components one more time). Call it from index.vue like that:
<template>
  <article-list query="tag=nuxt&state=rising" title="New Nuxt.js articles" />
</template>
  1. Use pages/_page.vue as the default route handler and place article list there (but it will require to move authors to the /authors/_username route, and tags to /?tag=.. query).

  2. Write the custom router in the nuxt.config.js.

  3. Convert pages/index.vue, pages/top.vue and pages/t/_tag.vue to the symlinks that point to the same common_pages/index.vue file and parse the route there manually.

@Kasheftin
Copy link
Author

About the 1 way... My mistake, the head method has to be called from the page-level component. Instead of sending title to the ArticleList.vue we could write something like:

<template>
  <article-list :query="query" />
</template>

<script>
export default {
  computed: {
    query() {
      switch (this.$route.name) {
        case 't-tag':
          return `tag=${this.$route.params.tag}&top=365`
        case 'top':
          return 'tag=nuxt&top=365'
        default:
          return 'tag=nuxt&state=rising'
      }
    }
  },
  head() {
    switch (this.$route.name) {
      case 't-tag':
        return {title: `${this.$route.params.tag} articles`}
      case 'top':
        return {title: 'Top Nuxt.js articles'}
      default
        return {title: 'New Nuxt.js articles'}
    }
  }
}
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant