前语
物理回来键通常是指手机左滑、右滑和机身自带的回来键。在安卓/IOS 端能够经过监听物理回来事情去封闭弹窗,可是在H5是没有这一事情,那应该怎么去完成物理回来键封闭弹窗呢?接下来说说我的计划。
淘宝作用
操作:产品详情 –>点击购物车进入 购买弹窗 –>点击图片进入 图片预览弹窗
回来操作:–>物理键回来 封闭图片预览弹窗 –>物理键再回来 封闭购买弹窗 –> 回到 产品详情
h5完成作用
vue3预览:xiaocheng555.github.io/physical-bu…
vue2预览:xiaocheng555.github.io/physical-bu…
源码(拿来吧你):github.com/xiaocheng55…
完成原理
物理回来键在H5实际上仅仅回来上一页的功能,也便是回退上个历史记载。因此咱们能够在弹窗翻开时,增加一个不会改动当时页面的历史记载,如 ?popyp=true
(或 #popup
),在触发物理回来键后,浏览器会撤退一个历史记载而且主动铲除?popyp=true
(或 #popup
),而页面不会发生跳转和改写,最终经过监听url变化,识别出url中 ?popyp=true
被铲除则封闭弹窗。
组件完成(Vue3)
将物理回来键封闭弹窗逻辑封装成弹窗组件:HistoryPopup.vue。
组件基础结构
<template>
<!-- van-popup 假如不设置 :lock-scroll="false",主动翻开弹窗会呈现页面锁住不能翻滚(vue2版别不会) -->
<van-popup v-model:show="dialogVisible" v-bind="$attrs" :lock-scroll="false">
<slot></slot>
</van-popup>
</template>
<script setup lang="ts">
import { Popup as VanPopup } from 'vant'
import { computed } from 'vue'
const props = defineProps({
modelValue: {
type: Boolean,
default: false
}
})
const emit = defineEmits([
'update:modelValue'
])
const dialogVisible = computed({
get () {
return props.modelValue
},
set (val) {
emit('update:modelValue', val)
}
})
</script>
经过 v-model
来操控弹窗显示躲藏
增加/删除历史记载
弹窗翻开时,增加 ?key=value
记载;弹窗封闭时,移除 ?key=value
记载
const props = defineProps({
...
// query参数的key值
queryKey: {
type: String
},
// query参数的value值,弹窗翻开会URL上显示`?queryValue=queryValue`
queryValue: {
type: [Number, String, Boolean],
default: true
}
})
watch(dialogVisible, (val) => {
if (val) {
onOpen()
} else {
onClose()
}
})
// 弹窗翻开事情
function onOpen () {
addQuery()
}
// 弹窗封闭事情
function onClose () {
removeQuery()
}
// 增加query参数
function addQuery () {
if (!existQueryKey()) {
const newQuery = { ... route.query }
if (props.queryKey) newQuery[props.queryKey] = props.queryValue
router.push({
query: newQuery
})
}
}
// 移除query参数
function removeQuery () {
if (props.queryKey && existQueryKey()) {
const newQuery = { ... route.query }
delete newQuery[props.queryKey]
router.replace({
query: newQuery
})
}
}
// 判别路由query上是否存在queryKey
function existQueryKey () {
const { query } = route
return props.queryKey && props.queryKey in query
}
主动翻开/封闭弹窗
-
弹窗处于翻开时,点击浏览器的撤退键,则主动封闭弹窗
-
弹窗处于封闭时,点击浏览器的前进键,则主动翻开弹窗
watch(() => route.query, () => {
if (!props.queryKey) return
const exist = existQueryKey()
// 主动封闭弹窗
if (!exist && dialogVisible.value) {
dialogVisible.value = false
}
// 主动翻开弹窗
if (exist && !dialogVisible.value) {
dialogVisible.value = true
}
})
作用如图:
多了一条历史记载的bug
当手动翻开弹窗时,url增加 ?popup=true
参数,同时也增加了一条历史记载;然后手动封闭弹窗,是经过 router.repalce()
来移除 ?popup=true
参数的,而 router.repalce()
是不会移除历史记载,那么一开始增加的历史纪录还存在,这就导致翻开并封闭弹窗会多了一条历史纪录。那么假如用户翻开封闭弹窗10次,就会多发生10条历史记载,用户在详情页回来主页时,就需要点11次回来按钮才能回到主页。
解决计划
用户翻开弹窗时,url的变化过程是:/detail
=> /detail?popup=true
,翻开弹窗后假如能知道上一页是 /detail
的话,那么在弹窗封闭时调用 router.back()
就能移除 ?popup=true
参数和多出的历史纪录了。
恰好,vue3 的 vue-router
会将上一页的地址记载在 window.history.state.back
上。完成如下:
// 弹窗封闭事情
function onClose () {
if (hasBackRecord()) {
router.back()
} else {
removeQuery()
}
}
// 判别弹窗是否有回来记载
function hasBackRecord () {
const state = window.history?.state
if (state && props.queryKey) {
if (!state.back) return false
const backRoute = router.resolve(state.back || '') // 解分出回来的路由
if (backRoute.path === route.path) {
const backQuery = backRoute.query // 上一页的query参数
const curQuery = route.query // 当时页query参数
return (props.queryKey in curQuery) && !(props.queryKey in backQuery)
}
return false
} else {
return false
}
}
完整代码
// HistoryPopup.vue
<template>
<!-- van-popup 假如不设置 :lock-scroll="false",主动翻开弹窗会呈现页面锁住不能翻滚(vue2版别不会) -->
<van-popup v-model:show="dialogVisible" v-bind="$attrs" :lock-scroll="false">
<slot></slot>
</van-popup>
</template>
<script setup lang="ts">
import { Popup as VanPopup, Overlay as VanOverlay } from 'vant'
import { computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const props = defineProps({
modelValue: {
type: Boolean,
default: false
},
queryKey: {
type: String
},
queryValue: {
type: [Number, String, Boolean],
default: true
}
})
const emit = defineEmits([
'update:modelValue'
])
const router = useRouter()
const route = useRoute()
// 操控弹窗显示
const dialogVisible = computed({
get () {
return props.modelValue
},
set (val) {
emit('update:modelValue', val)
}
})
// 弹窗翻开事情
function onOpen () {
addQuery()
}
// 弹窗封闭事情
function onClose () {
if (hasBackRecord()) {
router.back()
} else {
removeQuery()
}
}
// 判别弹窗是否有回来记载
function hasBackRecord () {
const state = window.history?.state
if (state && props.queryKey) {
if (!state.back) return false
const backRoute = router.resolve(state.back || '') // 解分出回来路由
if (backRoute.path === route.path) {
const backQuery = backRoute.query // 上一页的query参数
const curQuery = route.query // 当时页query参数
return (props.queryKey in curQuery) && !(props.queryKey in backQuery)
}
return false
} else {
return false
}
}
// 增加query参数
function addQuery () {
if (!existQueryKey()) {
const newQuery: any = { ... route.query }
if (props.queryKey) newQuery[props.queryKey] = props.queryValue
router.push({
query: newQuery
})
}
}
// 移除query参数
function removeQuery () {
if (props.queryKey && existQueryKey()) {
const newQuery: any = { ... route.query }
delete newQuery[props.queryKey]
router.replace({
query: newQuery
})
}
}
// url上是否存在queryKey
function existQueryKey () {
const { query } = route
return props.queryKey && props.queryKey in query
}
watch(dialogVisible, (val) => {
val ? onOpen() : onClose()
})
watch(() => route.query, () => {
if (!props.queryKey) return
const exist = existQueryKey()
// 主动封闭弹窗
if (!exist && dialogVisible.value) {
dialogVisible.value = false
}
// 主动翻开弹窗
if (exist && !dialogVisible.value) {
dialogVisible.value = true
}
}, {
immediate: true
})
</script>
组件用法
<HistoryPopup v-model.show="visible" queryKey="popup">
...
</HistoryPopup>
优化
优化多了一条历史记载的解决计划
前面提过,能够经过 history.state.back
来解决多了一条历史记载的问题,可是history.state.back
是vue3才有的,有些强相关了,是不是还有更优的解决计划呢?如下:
本来解决计划是:上一个url和当时url做比照就能知道弹窗多了 ?popup=true
历史记载,然后运用 router.back()
去封闭弹窗并消除多出的历史记载,不然运用 router.replace()
去封闭弹窗并消除 ?popup=true
参数。
优化计划:弹窗翻开并增加 ?popup=true
参数时,记载 history.state.popupKey
为 popup
, 那么封闭弹窗就运用 router.back()
;假如在新页签翻开地址 /#/detail?popup=true
,弹窗会主动翻开,此刻封闭弹窗,能够得知 history.state.popupKey
为 undefined
,那么封闭弹窗就运用 router.replace()
去消除 ?popup=true
参数。
// ⚠️更改处:设置 history.state 的值
function setHistoryState (state: any) {
history.replaceState({
...history.state,
...state
}, '')
}
// 弹窗翻开事情
function onOpen () {
addQuery()
}
// 弹窗封闭事情
function onClose () {
if (hasBackRecord()) {
router.back()
} else {
removeQuery()
}
}
// 判别弹窗是否有回来记载
function hasBackRecord () {
// ⚠️更改处:
return window.history.state?.popupKey === props.queryKey
}
// 增加query参数
async function addQuery () {
if (!existQueryKey()) {
const newQuery = { ... route.query }
if (props.queryKey) newQuery[props.queryKey] = props.queryValue?.toString?.() || ''
await router.push({
query: newQuery
})
// ⚠️更改处:
setHistoryState({
popupKey: props.queryKey
})
}
}
// 移除query参数
function removeQuery () {
if (props.queryKey && existQueryKey()) {
const newQuery = { ... route.query }
delete newQuery[props.queryKey]
router.replace({
query: newQuery
})
}
}
写成hook
回来键封闭弹窗逻辑都写在 HistoryPopup.vue
组件的话,假如还有其他弹窗如侧边栏弹窗,actionsheet弹窗等组件的话,有需要封装重复逻辑,所以回来键封闭弹窗逻辑写成hook,便利复用,具体见源码 src/hooks/useHistoryPopup.js
,组件运用如下:
<template>
<!-- van-popup 假如不设置 :lock-scroll="false",主动翻开弹窗会呈现页面锁住不能翻滚(vue2版别不会) -->
<van-popup v-model:show="dialogVisible" v-bind="$attrs" :lock-scroll="false">
<slot></slot>
</van-popup>
</template>
<script setup lang="ts">
import { Popup as VanPopup } from 'vant'
import useHistoryPopup, { historyPopupProps } from '@/hooks/useHistoryPopup'
defineProps({
...historyPopupProps
})
const { dialogVisible } = useHistoryPopup()
</script>
Vue2完成
vue2 完成跟 vue3 完成差不多,仅有的区别便是vue2的 vue-route
不会将上一页信息记载在 window.history.state.back
中,这就需要自己去扩展 vue-router
,手动完成window.history.state.back
。
扩展路由
首要重写 $router.push()
, $router.replace
办法,并在跳转后给 window.history.state
对象增加 back
, current
, forward
等信息。除此之外,还需在初次加载、手动输入地址并跳转时,设置 window.history.state
信息。
// router-extend.js
// 扩展路由历史记载的状况信息【支持版别vue-router@3.6.4,版别不能太低】
export function extendHistoryState (router) {
// 设置history.state的值
function setHistoryState (state) {
history.replaceState({
...history.state,
...state
}, '')
}
// 初次进入页面记载当时路由信息
let once = true
function setRouteStateAtFirst () {
// 此处不能毁掉afterEach,假如毁掉了,在其他地方运用afterEach勾子,初次不会触发改勾子回调
router.afterEach((route) => {
if (!once) return
once = false
setHistoryState({
back: history.state?.back || null,
current: route.fullPath,
forward: history.state?.forward || null
})
})
}
// 监听popstate,当手动输入地址跳转其他页面时,记载路由信息
function handlePopstate () {
if (history.state?.current) return
const from = router.currentRoute
// 记载跳转后的路由信息
const destroy = router.afterEach((to) => {
setHistoryState({
back: from.fullPath,
current: to.fullPath,
forward: null
})
destroy()
})
}
const { push, replace } = router
// 重写router.push
function routerPush (location, onComplete, ...rest) {
const to = router.resolve(location)
const fromPath = router.currentRoute.fullPath
// 记载跳转前的路由信息
if (to) {
setHistoryState({
back: history.state?.back || null,
current: fromPath,
forward: to.route.fullPath
})
}
// 记载跳转后的路由信息
const complete = (...args) => {
const curPath = router.currentRoute.fullPath
setHistoryState({
back: fromPath,
current: curPath,
forward: null
})
onComplete && onComplete.apply(router, args)
}
return push.apply(router, [location, complete, ...rest])
}
// 重写router.replace
function routerReplace (location, onComplete, ...rest) {
// 记载跳转后的路由信息
const complete = (...args) => {
const curPath = router.currentRoute.fullPath
setHistoryState({
back: history.state?.back || null,
current: curPath,
forward: history.state?.forward || null
})
onComplete && onComplete.apply(router, args)
}
return replace.apply(router, [location, complete, ...rest])
}
setRouteStateAtFirst()
window.addEventListener('popstate', handlePopstate)
router.push = routerPush
router.replace = routerReplace
}
运用 extendHistoryState
:
import Router from 'vue-router'
import { extendHistoryState } from './router-extend'
const router = new Router(...)
extendHistoryState(router)
组件
<template>
<van-popup v-model="dialogVisible" v-bind="$attrs">
<slot></slot>
</van-popup>
</template>
<script>
export default {
name: 'HistoryPopup',
props: {
modelValue: {
type: Boolean,
default: false
},
queryKey: {
type: String
},
queryValue: {
type: [Number, String, Boolean],
default: true
}
},
model: {
prop: 'modelValue',
event: 'modelValueChange'
},
computed: {
dialogVisible: {
get () {
return this.modelValue
},
set (val) {
this.$emit('modelValueChange', val)
}
}
},
methods: {
// 弹窗翻开事情
onOpen () {
this.addQuery()
},
// 弹窗封闭事情
onClose () {
if (this.hasBackRecord()) {
this.$router.back()
} else {
this.removeQuery()
}
},
// 判别弹窗是否有回来记载
hasBackRecord () {
const state = window.history?.state
if (state && this.queryKey) {
if (!state.back) return false
const backRoute = this.$router.resolve(state.back || '') // 解分出回来路由
if (backRoute.path === this.$routepath) {
const backQuery = backRoute.query || {} // 上一页的query参数
const curQuery = this.$route.query || {} // 当时页query参数
return (this.queryKey in curQuery) && !(this.queryKey in backQuery)
}
return false
} else {
return false
}
},
// 增加query参数
addQuery () {
if (!this.existQueryKey()) {
const newQuery = { ... this.$route.query }
if (this.queryKey) newQuery[this.queryKey] = this.queryValue?.toString?.()
this.$router.push({
query: newQuery
})
}
},
// 移除query参数
removeQuery () {
if (this.queryKey && this.existQueryKey()) {
const newQuery = { ... this.$route.query }
delete newQuery[this.queryKey]
this.$router.replace({
query: newQuery
})
}
},
// url上是否存在queryKey
existQueryKey () {
const { query } = this.$route
return this.queryKey && this.queryKey in query
}
},
watch: {
dialogVisible (val) {
val ? this.onOpen() : this.onClose()
},
'$route.query': {
immediate: true,
handler () {
if (!this.queryKey) return
const exist = this.existQueryKey()
// 主动封闭弹窗
if (!exist && this.dialogVisible) {
this.dialogVisible = false
}
// 主动翻开弹窗
if (exist && !this.dialogVisible) {
this.dialogVisible = true
}
}
}
}
}
</script>
<style lang='less' scoped>
</style>
优化
vue2优化跟vue3优化同理,详见源码 根目录/vue2/
:
1、无需选用扩展路由写法 2、回来键封闭弹窗逻辑写为mixin,便利复用
结束
至此,H5完成物理回来键封闭弹窗完成,功能包含:
-
物理回来键封闭弹窗
-
支持多级弹窗嵌套
-
支持弹窗跳转
-
无多余历史记载
最终附上地址
vue3预览:xiaocheng555.github.io/physical-bu…
vue2预览:xiaocheng555.github.io/physical-bu…
源码:github.com/xiaocheng55…