Vue Router:保留查询参数并为子节点使用相同的视图

off*_*ffz 7 vue-router vuejs2

我正在用Vue重写现有的Angular 1应用程序.

该应用程序总是需要由用户进行身份验证locale,idtoken进入任何意见之前.尊重API的约定,我token在主要父路由中指定了一个查询参数.

来自现有的Angular的UI路由器实现,我认为这是要走的路:

// main.js
new Vue({
  el: '#app',
  router,
  store,
  template: '<router-view name="main"></router-view>'
})

// router.js
const router = new Router({
  mode: 'history',
  routes: [
    {
      name: 'start',
      path : '/:locale/:id', // /:locale/:id?token didn't work
      query: {
        token: null
      },
      beforeEnter (to, from, next) {
        // 1. Get data from API via locale, id and token
        // 2. Update store with user data
      },
      components: {
        main: startComponent
      },
      children: [{
        name: 'profile',
        path: 'profile',
        components: {
          main: profileComponent
        }
      }]
    }
  ]
})    
Run Code Online (Sandbox Code Playgroud)

当我浏览到的profile观点,我希望更改视图和查询令牌留下来,如/en-US/123?token=abc/en-US/123/profile?token=abc.都没有发生.

我正在使用Vue 2.3.3和Vue Router 2.3.1.

问题:

  • 导航到子路由时,我可以保留查询参数吗?
  • 我在这里使用Vue路由器吗?或者我需要责怪我的UI路由器偏见?

mbr*_*int 18

您可以在Router的全局挂钩中解决此问题

import VueRouter from 'vue-router';
import routes from './routes';

const Router = new VueRouter({
  mode: 'history',
  routes
});

function hasQueryParams(route) {
  return !!Object.keys(route.query).length
}

Router.beforeEach((to, from, next) => {
   if(!hasQueryParams(to) && hasQueryParams(from)){
    next({name: to.name, query: from.query});
  } else {
    next()
  }
})
Run Code Online (Sandbox Code Playgroud)

如果新路由(to)没有自己的参数,那么它们将从前一个路由中获取(from)

  • 实际上使用`toWithQuery = Object.assign({},to,{query:from.query}); next(toWithQuery);`更健壮 (4认同)
  • 我有可选的动态路由,因此当有参数时我的路由会阻塞。但这是有效的:`next({ ...to, query: from.query });` (2认同)