通过手机物理返回键实现弹出层的隐藏
![图片描述 图片描述](https://i-blog.csdnimg.cn/blog_migrate/1739af1c7d781aa08a0de379be438971.png)
<template>
<div class="popup">
<h1 @click="popup">返回键隐藏弹出层</h1>
<div class="pop" :class="{up: flag}">弹出层文本
<--点击关闭实现弹出层隐藏-->
<span class="close" @click="close">关闭</span>
</div>
</div>
</template>
<script>
/*
* 总的实现思想即为通过一个开关的true或false值来判断是否需要来添加一条空的历史记录
* */
export default {
data() {
return {
flag: false
}
},
mounted() {
// 当添加历史记录时,通过window下绑定popstate函数进行监听
if (window.history && window.history.pushState) {
window.addEventListener('popstate', (e) => {
this.flag = false
})
}
},
methods: {
popup() {
// 通过class名up的开关flag实现是否通过window.history.pushState添加一条空的历史记录
if (!this.flag) {
window.history.pushState(null, null, '')
}
this.flag = true
},
close() {
// 点击关闭时,减少一条历史记录
window.history.go(-1)
this.flag = false
}
}
}
</script>
<style scoped lang="stylus">
/* 此处用的stylus预编译器 */
.popup
width 100vw
height 100vh
overflow hidden
position relative
h1
text-align center
font-size 50px
line-height 80px
.pop
width 100vw
height 30vh
text-align center
line-height 30vh
font-size 40px
background-color lightgray
position absolute
left 0
bottom -30vh
transition all 800ms
.up
bottom 0
.close
width 60px
height 40px
line-height normal
position absolute
right 0
top 0
font-size 28px
color red
</style>