vue模拟原生app中物理回退键关闭当前弹出层

在原生app中,通过监听物理回退键可以对当前弹出层进行关闭,再次点击会回退到上一个页面,这次介绍一下vue中如何实现类似的效果

实现这一效果所需要的原料

  1. 弹出层
    这里的弹出层已mint-ui的pupup为例子
    通过一个cell来点开弹出层
    {{showInfo.del_area}}

...//弹出层

data(){ return{ del_area:false, cur_type:''//存储当前弹出层的值 } }

此处v-model中的值是关键,控制弹出层的显示和隐藏,data中默认初始化为false

2.相关函数和计算属性
函数:open
open(params){ this[params.type]=true this.cur_type = params.type//将当前弹出层的属性保存 }

计算属性:fixedkey
//若当前弹出层打开,保存当前弹出层的v-model,否则移除 fixedkey(){ if(this[this.cur_type]){ this.savePopup(this.cur_type) }else{ this.removePopup() } return this[this.cur_type] }

此处的savePopup(value)和removePopup()全局通用,写在vue自定义插件中,弹出的值存入sessionStorage中的数组中

3.vue自定义插件模块
export default{ install(Vue){ // 向Vue对象上添加方法,保存popup值 Vue.prototype.savePopup = (value) => { //如果存在-新增,否则-创建 if(sessionStorage.getItem('popupArr')){ let tempArr = JSON.parse(sessionStorage.getItem('popupArr')) tempArr.push(value) sessionStorage.setItem('popupArr',JSON.stringify(tempArr)) }else{ let arr = [value] sessionStorage.setItem('popupArr',JSON.stringify(arr)) } }, Vue.prototype.removePopup = () =>{ if(sessionStorage.getItem('popupArr')){ let tempArr = JSON.parse(sessionStorage.getItem('popupArr')) tempArr.pop() sessionStorage.setItem('popupArr',JSON.stringify(tempArr)) } } } }

4.组件内路由钩子
beforeRouteLeave (to, from, next) { if(sessionStorage.getItem('popupArr')){ let tempArr = JSON.parse(sessionStorage.getItem('popupArr')) if(tempArr.length>0){ let cur = tempArr.pop() this[cur] = false sessionStorage.setItem('popupArr',JSON.stringify(tempArr)) next(false) }else{ next() } }else{ next() } }

技术栈:vue+vue-router+mint-ui 这个应该是比较偏僻的需求了,描述不周,敬请见谅

你可能感兴趣的:(vue模拟原生app中物理回退键关闭当前弹出层)