vue 路由

这篇博客探讨了在Vue项目中,由于iOS设备不解析URL中的#号导致的分享页面无法正常打开的问题。作者提供了多种解决方案,包括使用history模式、路由守卫重定向、创建中转页面等,以确保在微信分享后仍能正确跳转到目标页面。
摘要由CSDN通过智能技术生成

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值