最近作一個表單頁面,全部的交互效果都是到最後表單保存提交才實現的數據交互,所以出現用戶可能不保存頁面,而離開此頁面,形成數據損失,爲了不這樣的狀況,特地作一個彈窗提示功能,用watch監聽數據,若是數據發生變化,用戶點擊了其餘地方連接要離開頁面,則根據beforeRouteLeave離開該頁面時出發的衛士,從而出現彈窗提示,讓用戶選擇是否離開次頁面,若是watch監聽數據沒發生變化,則沒必要提示。 vue
監聽代碼以下:watch: {
datas: {
handler (val) {
if (val) {
this.count++
}
},
deep: true
}
},
複製代碼
判斷數據變化的次數,由於剛加載數據未徹底加載的時候,datas是空對象,待加載完以後,則出現一次數據變化, deep主要是深層次監聽,由於數據是層層對象,比較複雜 判斷要離開的代碼是:vuex
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()
}
},
複製代碼
彈窗觸發的事件方法以下:bash
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)
}
複製代碼
總體代碼以下:ui
<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:this
<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>
複製代碼