最近做一个表单页面,所有的交互效果都是到最后表单保存提交才实现的数据交互,因此出现用户可能不保存页面,而离开此页面,造成数据损失,为了避免这样的情况,特意做一个弹窗提示功能,用watch监听数据,如果数据发生变化,用户点击了其他地方链接要离开页面,则根据beforeRouteLeave离开该页面时出发的卫士,从而出现弹窗提示,让用户选择是否离开次页面,如果watch监听数据没发生变化,则不必提示。
在这里插入图片描述
监听代码如下:
watch: {
datas: {
handler (val) {
if (val) {
this.count++
}
},
deep: true
}
},
判断数据变化的次数,因为刚加载数据未完全加载的时候,datas是空对象,待加载完之后,则出现一次数据变化, deep主要是深层次监听,因为数据是层层对象,比较复杂
判断要离开的代码是:
beforeRouteLeave (to, from, next) {
// 判断数据是否修改,如果修改按这个执行,没修改,则直接执行离开此页面
if (this.count > 1) {
if (this.status) {
next()
return
}
// 弹窗显示
this.$refs.leaveTip.changeLimitDialog(true)
this.leave = to
next(false)
} else {
next()
}
},
弹窗触发的事件方法如下:
leavelHandler (b) {
const { leave } = this
if (b) {
// 主要判断是否触发弹窗事件了,
this.status = true
this.$router.push({ name: leave.name, query: leave.query, params: leave.params })
} else {
this.status = false
}
this.$refs.leaveTip.changeLimitDialog(false)
}
整体代码如下:
<template>
<div class="collect-box">
<crumb-tit>
<span slot="breadTit">提交信息配置</span>
<span slot="secondTit">提交信息配置</span>
</crumb-tit>
<main-i />
<leave-tip-dialog
ref="leaveTip"
@leavelHandler="leavelHandler"
>
<div slot="tip-slot">
有部分配置变更尚未保存,<br>
确定要离开当前页面妈
</div>
</leave-tip-dialog>
</div>
</template>
<script>
import CrumbTit from '@/components/pc/config/CrumbTit'
import MainI from '@/components/pc/config/collect/MainLayout'
import LeaveTipDialog from '@/components/pc/LeaveTipDialog'
import { mapState } from 'vuex'
export default {
components: {
MainI,
CrumbTit,
LeaveTipDialog
},
data () {
return {
leave: {},
status: false,
count: 0
}
},
computed: {
...mapState('config/collect', ['datas', 'datasReady'])
},
watch: {
datas: {
handler (val) {
if (val) {
this.count++
}
},
deep: true
}
},
beforeRouteLeave (to, from, next) {
if (this.count > 1) {
if (this.status) {
next()
return
}
this.$refs.leaveTip.changeLimitDialog(true)
this.leave = to
next(false)
} else {
next()
}
},
mounted () {
},
methods: {
leavelHandler (b) {
const { leave } = this
if (b) {
this.status = true
this.$router.push({ name: leave.name, query: leave.query, params: leave.params })
} else {
this.status = false
}
this.$refs.leaveTip.changeLimitDialog(false)
}
}
}
</script>
弹窗LeaveTipDialog:
<template>
<a-modal
:visible.sync="TipDialogVisible"
width="400px"
class="member-limit-dialog-box "
:footer="null"
@cancel="TipDialogVisible=false"
>
<div
class="dialog-tip-box"
>
<i class="icon iconfont iconicon-test68" />
<h2>注意</h2>
<div class="d-tip-con">
<slot name="tip-slot" />
</div>
<div class="limit-btn-box">
<a-button
type="primary"
@click="leavelHandler(false)"
>
留在页面
</a-button>
<a-button
class="ml-16"
@click="leavelHandler(true)"
>
离开页面
</a-button>
</div>
</div>
</a-modal>
</template>
<script>
export default {
data () {
return {
TipDialogVisible: false
}
},
computed: {
cId () {
return this.orgItemData.cid
}
},
methods: {
changeLimitDialog (b) {
this.TipDialogVisible = b
},
leavelHandler (b) {
this.$emit('leavelHandler', b)
}
}
}
</script>
网友评论