vue 路由
在vue-router路由对象中,路由有两种模式:hash和history,而默认的是hash模式。
之前公司H5项目采用hash模式,遇到苹果手机解析不了hash路由页面进不去,采用history模式根据开发/生产环境不同改写路劲
ios系统url上#后面的信息不会解析,会被忽略掉
比如url:www.demo.com/dist/index.html#/detail?id=10
直解析到www.demo.com/dist/index.html,所以跳转到首页
router/index.js
const router = new VueRouter({
mode: 'history',
base:process.env.NODE_ENV === 'production' ?'/45561/':'./',
routes
})
vue.config.js
module.exports = {
outputDir:"dist",
assetsDir:"static",
productionSourceMap: false,
// publicPath: './',
publicPath: process.env.NODE_ENV === 'production' ?'https://xxxx.cn/45561/':'./',
}
H5端分享页面时,微信会在域名和参数间自动添加类似“?/&from=singlemessage”字段且“#”后面的字段会被删除,导致分享页面只能进入首页,例子如下:
正常链接:https://xxx.cn/#/page/details/details
分享出去的链接被打开之后变成了:https://xxx.cn/?from=singlemessage&isappinstalled=0
把#后面都吃了
.从分享入手
//页面创建之前
beforeCreate() {
var url=location.href;
var targeturl=url.split("target=")[1];
//"target="后面的参数为实际页面参数
var tourl='https://www.xxx.cn/xxx.html/#'+targeturl;
location.href=tourl;
},
//前端分享页面
var localUrl=location.href;
//去掉链接里微信自动添加的字段
localUrl= shareUrl.replace(/&from=singlemessage/g, '');
localUrl= shareUrl.replace(/\?from=singlemessage/g, '');
var shareUlr="https://www.xxx.cn/xx.html?target="+localUrl.split("#")[1];
但是我在测试的时候把模式改成hash模式并没有复现这个问题
.路由守卫
router.beforeEach((to, from, next) => {
let url = window.location.href;
if (url.includes('?from=')) { // 判断是否携带了 from 参数,这一步灵活变通,只要能判断出是从微信分享链接进来的就 OK
url = url.replace(/cn.+.#/, 'cn/#'); // 利用正则表达式去掉微信携带的 ?from=singlemessage&isappinstalled=0 这串参数,如果这串参数对于你当前的页面有用处的话,可以重新拼接到你正常的链接后面去
window.location.href = url; // 重定向到正常链接
}
})
.前端页面中转,重定向
1、新建中转页
在 public 文件夹里新建一个 html 页面(与项目中 index.html 同级),命名为 redirect.html,文件内容如下:
<script>
let url = location.href.split('?')
let params = url[1].split('&')
let data = {}
params.forEach((n, i) => {
let p = n.split('=')
data[p[0]] = p[1]
})
if (!!data.shareRedirect) {
window.location.href = decodeURIComponent(data.shareRedirect)
}
</script>
2、组装分享链接
把要分享的链接,设置为中间页面的路径
let shareLink = 'https://lchd.cn/#/article?id=1';
shareLink = window.location.href.split('#')[0] + 'redirect.html?shareRedirect=' + encodeURIComponent(shareLink);