vue單頁面在微信下只能分享落地頁的解決方案
實際上關鍵詞叫 微信pushState只能分享落地頁 更貼切一點
應用場景:
- vue + vue-router
- vue-router使用hash模式(history模式?jīng)]試過)
- 不使用微信的js-sdk(因為我這個項目是可配置域名的商城,比較特殊,不能使用微信sdk)
這個方案并不是最優(yōu)秀的,會對性能造成一定的影響
HTML5 history.pushState
vue-router的內部是通過 history.pushState 和 history.replaceState 實現(xiàn)的。但是iOS設備的微信瀏覽器不會去檢測它們的變化。但是我們可以通過更新 location.href 讓微信瀏覽器識別到當前的url。
// vue-router/src/util/push-state.js
export function pushState (url?: string, replace?: boolean) {
saveScrollPosition()
// try...catch the pushState call to get around Safari
// DOM Exception 18 where it limits to 100 pushState calls
const history = window.history
try {
if (replace) {
history.replaceState({ key: _key }, '', url)
} else {
_key = genKey()
history.pushState({ key: _key }, '', url)
}
} catch (e) {
window.location[replace ? 'replace' : 'assign'](url)
}
}
export function replaceState (url?: string) {
pushState(url, true)
}
解決方法
window.location.href = window.location.href ,這段代碼可以讓微信記錄當前的url,且不會刷新頁面??梢栽赼pp.vue中 watch $route 在每次頁面更新的時候執(zhí)行一次。
// app.vue
watch: {
$route: {
immediate: true,
deep: true,
handler(to) {
// 微信瀏覽器判斷
const WECHAT_BROWSER = navigator.userAgent.toLowerCase().includes('micromessenger')
// 解決iOS微信瀏覽器分享地址只能是落地頁的問題,這個操作是不會刷新頁面的,query參數(shù)改變也會執(zhí)行
if (WECHAT_BROWSER) {
// eslint-disable-next-line
window.location.href = window.location.href
}
}
},
使用了上述方法可以解決這個問題,但是這會引出一個很奇葩的問題,在真機上進入 http://192.168.1.5:8080 和 http://192.168.1.5:8080/#/ 這兩個頁面,其中有一個鏈接的bug依然存在。原因具體不清楚,經(jīng)過測試可以在入口文件(main.js)中在頁面還沒有展示內容前刷新一次頁面,即可解決這個問題。
// main.js
// 微信瀏覽器判斷
const WECHAT_BROWSER = navigator.userAgent.toLowerCase().includes('micromessenger')
// 在url插入的search參數(shù),可以隨意,但是必須要
// 例:http://192.168.1.5:8080/?_wx_=1#/
const wxQuery = '_wx_=1'
const isRepeatQuery = location.search.includes(wxQuery)
if (WECHAT_BROWSER && !isRepeatQuery) {
const unit = (location.search && location.search !== '?') ? '&' : '?'
location.search += unit + wxQuery // 添加_wx_參數(shù),該操作會刷新頁面
}
上面的代碼之所以要在 hash 前面加一個 ?_wx_=1 參數(shù),為了方便刷新頁面給一個標志位判斷是否已刷新。參數(shù)的 key-value 隨意。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue3初探之ref、reactive以及改變數(shù)組的值
在setup函數(shù)中,可以使用ref函數(shù)和reactive函數(shù)來創(chuàng)建響應式數(shù)據(jù),下面這篇文章主要給大家介紹了關于Vue3初探之ref、reactive以及改變數(shù)組值的相關資料,需要的朋友可以參考下2022-09-09

