Vue3返回关闭弹窗不返回页面
原创
©著作权归作者所有:来自51CTO博客作者明知山的原创作品,请联系作者获取转载授权,否则将追究法律责任
完整代码
按钮和弹窗为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>