完整代码
按钮和弹窗为vant
组件,需自行引入
<template>
<van-button @click="showPop()">点击弹窗</van-button>
<van-popup
v-model:show="state.isPop"
position="bottom"
:style="{ height: '30%' }"
@close="addPopState()"
/>
</template>
<script setup>
import { reactive, onMounted, onBeforeUnmount } from "vue"
import { useRouter } from "vue-router"
const router = useRouter()
const state = reactive({
isPop: false
})
onMounted(() => {
window.addEventListener("popstate", addPopState, false);
})
onBeforeUnmount(() => {
window.removeEventListener("popstate", addPopState, false)
})
const showPop = () => {
state.isPop = true
window.history.pushState(null, null, "#");
}
const addPopState = () => {
if (state.isPop) {
state.isPop = false
} else {
router.go(-1);
}
}
</script>