Vue3返回关闭弹窗不返回页面

2022-05-05 20:12:01 浏览数 (2)

完整代码 按钮和弹窗为vant组件,需自行引入

代码语言:javascript复制
<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>

0 人点赞