實際上關(guān)鍵詞叫 微信pushState只能分享落地頁 更貼切一點
應(yīng)用場景:
這個方案并不是最優(yōu)秀的,會對性能造成一定的影響
HTML5 history.pushState
vue-router的內(nèi)部是通過 history.pushState 和 history.replaceState 實現(xiàn)的。但是iOS設(shè)備的微信瀏覽器不會去檢測它們的變化。但是我們可以通過更新 location.href 讓微信瀏覽器識別到當(dāng)前的url。
// vue-router/src/util/push-state.jsexport 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 ,這段代碼可以讓微信記錄當(dāng)前的url,且不會刷新頁面??梢栽赼pp.vue中 watch $route 在每次頁面更新的時候執(zhí)行一次。
// app.vuewatch: { $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 } }},使用了上述方法可以解決這個問題,但是這會引出一個很奇葩的問題,在真機上進(jìn)入 http://192.168.1.5:8080 和 http://192.168.1.5:8080/#/ 這兩個頁面,其中有一個鏈接的bug依然存在。原因具體不清楚,經(jīng)過測試可以在入口文件(main.js)中在頁面還沒有展示內(nèi)容前刷新一次頁面,即可解決這個問題。
// 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ù),為了方便刷新頁面給一個標(biāo)志位判斷是否已刷新。參數(shù)的 key-value 隨意。
新聞熱點
疑難解答