vue设置全局query参数

router.beforeEach((to, from, next) => {
  // 设置全局店铺ID shopid
  const shopid = from.query.shopid
  // 如果没有shopid 先跳转到总店 shopid为1
  if (!shopid && !to.query.shopid) {
    router.replace({
      path: '/',
      query: { 'shopid': 1 }
    })
    return false
  }
  // 此处通过修改push给query增加shopid的方式, 会重置跳转数据.
  // 这会影响到replace跳转, 导致变成正常push跳转.
  // 如果原跳转是replace方式, 需要在query里主动添加shopid. 避免被重置数据.
  if (shopid && (shopid !== to.query.shopid)) {
    // 如果传递了shopid 走正常路由
    // 否则先手动添加shopid参数
    if (!to.query.shopid) {
      to.query.shopid = shopid
      router.push({
        path: to.path,
        query: to.query
      })
      return false
    }
  }

  // 设置页面标题
  const title = to.meta && to.meta.title
  if (title) {
    document.title = title
  }

  // 是否登录
  if (!store.get('token')) {
    // 需要登录
    if (to.meta && to.meta.requiresAuth) {
      next({
        path: '/',
        query: { 'shopid': 1 },
        replace: true
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

 

posted @ 2019-04-17 10:16  这个男人  阅读(5289)  评论(0编辑  收藏  举报