1

I want to add a route with query params.
If the url is blog, then navigate to index page.
If the url includes the author query param, replace a component on the page with the BlogAuthorPage component.

router: {
  extendsRoutes(routes, resolve) {
    routes.push({
      name: 'author-page-detail',
      path: '/blog?author=*',
      component: resolve(__dirname, 'pages/blog/author-page.vue')
    })
  }
}

2 Answers 2

1

This should not be done in nuxt.config.js's router key but rather in your blog.vue page directly with a component router guard.
The code below should be enough to check if the route does have a author query params and redirect to the blog/author-page page.

<script>
export default {
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (vm.$route.query?.author) next({ name: 'blog-author-page' })
      else next()
    })
  },
}
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

I don't redirect toan another page, I want to stay on a current page and substitute the main component of a page.
Then, you need to make the same kind of check inside of a fetch() or asyncData() hook and use a dynamic component. Can you share your .vue component?
1

I use "@nuxtjs/router": "^1.6.1",

  • nuxt.config.js
  /*
  ** @nuxtjs/router module config
  */
  routerModule: {
    keepDefaultRouter: true,
    parsePages: true
  }
  • router.js
import Vue from 'vue'
import Router from 'vue-router'

import BlogIndexPage from '~/pages/blog/index'
import BlogAuthorPage from '~/pages/blog/author-page';

Vue.use(Router);

export function createRouter(ssrContext, createDefaultRouter, routerOptions, config) {
  const options = routerOptions ? routerOptions : createDefaultRouter(ssrContext, config).options

  return new Router({
    ...options,
    routes: [
      ...options.routes,
      {
        path: '/blog',
        component: ssrContext.req.url.includes('/blog?author') ? BlogAuthorPage : BlogIndexPage
      }
    ]
  })
}

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.