哈希路由公众号问题

109 阅读1分钟

vue-router新发现

当query里有url时 $route.query.code

  • 这种url后面的code获取不到 //需要把code及后面的全都移到路由参数首位
http://ckft9m.natappfree.cc/#/news?url=https%3A%2F%2Fchcms.xinqshi.com%2Fwxhelp%2F6cbe14c7-d1c3-460a-aa8d-94056584d2c31672999809371.pdf&code=061A8t0w3sEKu03fxk0w3Vq7dH0A8t0e&state=STATE
  • 这种url后面的code可以获取到(然而一般不会在链接里这么写url参数 即使跳转的地址是这个,跳转链接后网址里的也是encode后的,也就是上面那种格式)
http://ckft9m.natappfree.cc/#/news?url=https://chcms.xinqshi.com/wxhelp/6cbe14c7-d1c3-460a-aa8d-94056584d2c31672999809371.pdf&code=061A8t0w3sEKu03fxk0w3Vq7dH0A8t0e&state=STATE

第二种情况之所以获取不到code

哈希模式公众号授权跳转回来链接格式化

方法一:(老方案,推荐第二个)

import router from './router'

// 微信授权后 回调的路由是乱的,捋顺后重新跳
router.beforeEach((to, from, next) => {
  let url = window.location.href
  if (url.indexOf('/?code') > -1) {
    const hasQuery = url.match(/\?/g)
    let path = url.match(/#.*$/)
    url = url.replace(/#.*$/, '')
    url = url.replace(/\/\?/, `/${path[0]}${hasQuery.length > 1 ? '&' : '?'}`)
    // ---把code移到最前面(防止链接里有url时,导致url=xxx&code=xxx这种情况获取不到code)
    if (/\&code/.test(url)) {
      let wxSec = url.match(/code.*/)
      url = url.replace(/&code.*/, '')
      url = url.replace(/\?/, () => `?${wxSec[0]}&`)
    }

    window.location.href = url
    return
  }
  next()
})

优化

router.beforeEach(async (to, from, next) => {
  const href = window.location.href
  if (href.indexOf('/?code') > -1) {
    const cleanUrl = window.location.protocol + '//' +
      window.location.host +
      window.location.pathname +
      window.location.hash + window.location.search
    window.location.href = cleanUrl
  } else {
    next()
  }
})