實(shí)際上關(guān)鍵詞叫 微信pushState只能分享落地頁(yè) 更貼切一點(diǎn)
應(yīng)用場(chǎng)景:
這個(gè)方案并不是最優(yōu)秀的,會(huì)對(duì)性能造成一定的影響
HTML5 history.pushState
vue-router的內(nèi)部是通過(guò) history.pushState 和 history.replaceState 實(shí)現(xiàn)的。但是iOS設(shè)備的微信瀏覽器不會(huì)去檢測(cè)它們的變化。但是我們可以通過(guò)更新 location.href 讓微信瀏覽器識(shí)別到當(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,且不會(huì)刷新頁(yè)面。可以在app.vue中 watch $route 在每次頁(yè)面更新的時(shí)候執(zhí)行一次。
// app.vuewatch: { $route: { immediate: true, deep: true, handler(to) { // 微信瀏覽器判斷 const WECHAT_BROWSER = navigator.userAgent.toLowerCase().includes('micromessenger') // 解決iOS微信瀏覽器分享地址只能是落地頁(yè)的問(wèn)題,這個(gè)操作是不會(huì)刷新頁(yè)面的,query參數(shù)改變也會(huì)執(zhí)行 if (WECHAT_BROWSER) { // eslint-disable-next-line window.location.href = window.location.href } }},使用了上述方法可以解決這個(gè)問(wèn)題,但是這會(huì)引出一個(gè)很奇葩的問(wèn)題,在真機(jī)上進(jìn)入 http://192.168.1.5:8080 和 http://192.168.1.5:8080/#/ 這兩個(gè)頁(yè)面,其中有一個(gè)鏈接的bug依然存在。原因具體不清楚,經(jīng)過(guò)測(cè)試可以在入口文件(main.js)中在頁(yè)面還沒(méi)有展示內(nèi)容前刷新一次頁(yè)面,即可解決這個(gè)問(wèn)題。
// 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ù),該操作會(huì)刷新頁(yè)面}上面的代碼之所以要在 hash 前面加一個(gè) ?_wx_=1 參數(shù),為了方便刷新頁(yè)面給一個(gè)標(biāo)志位判斷是否已刷新。參數(shù)的 key-value 隨意。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注