如何讓用戶選擇是否離開當(dāng)前頁面?
為什么要讓用戶選擇是否離開頁面
- 如果用戶填寫了很多數(shù)據(jù)此時(shí)
- 不小心點(diǎn)了其他a標(biāo)簽或者關(guān)閉了瀏覽器,不做判斷,那么用戶數(shù)據(jù)直接丟了
梳理需求
- 離開頁面方式,被location.href,a標(biāo)簽,關(guān)閉瀏覽器或者當(dāng)前tab頁等...
- 需要判斷數(shù)據(jù)是否跟初始化時(shí)一致(用戶有無填寫表單...)
- 用戶選擇離開就要繼續(xù)邏輯,反之則不離開
正式開始
- 首先要知道一個(gè)事件:onbeforeunload,MDN的說明是:當(dāng)瀏覽器窗口關(guān)閉或者刷新時(shí),會(huì)觸發(fā)beforeunload事件。當(dāng)前頁面不會(huì)直接關(guān)閉,可以點(diǎn)擊確定按鈕關(guān)閉或刷新,也可以取消關(guān)閉或刷新。
- HTML規(guī)范指出在此事件中調(diào)用window.alert(),window.confirm()以及window.prompt()方法,可能會(huì)失效
實(shí)踐一下
- 在微信公眾號(hào)編輯器界面,輸入一部分內(nèi)容后,點(diǎn)擊關(guān)閉tab頁,此時(shí)出現(xiàn)彈窗
- 刪除所有內(nèi)容后,回歸初始進(jìn)入的數(shù)據(jù),點(diǎn)擊關(guān)閉tab頁,直接就關(guān)閉了,沒有出現(xiàn)提示
- 看插件顯示,這個(gè)編輯器界面沒有使用react和vue,應(yīng)該是jq吧,測(cè)試下控制臺(tái),對(duì)的,一猜就中(小編太🐂了,不點(diǎn)個(gè)關(guān)注?)
回到項(xiàng)目中,加入beforeunload事件
- HTML文件中加入script標(biāo)簽
- <script type="text/javascript">
- window.onbeforeunload = function () {
- return "Leave this page?";
- }
- </script>
- 點(diǎn)擊關(guān)閉,或者此時(shí)輸入window.location.href= "xxx.ooo.com"會(huì)出現(xiàn)
- 那么問題來了,如果我通過a標(biāo)簽跳轉(zhuǎn)呢?
通過a標(biāo)簽跳轉(zhuǎn)(+前端路由)
- 我使用的是dva/router,引入相關(guān)組件
- import { Prompt } from 'dva/router';
- ....
- render(){
- return <Prompt message={this.handlePrompt} />
- }
- 引入Prompt組件,并且傳入message是一個(gè)方法,看看這個(gè)方法
- public handlePrompt = (location: Location) => {
- return false;
- };
- 那么此時(shí)我們使用dva/router的history.push方法去跳轉(zhuǎn)前端路由,就不能跳了,因?yàn)閔andlePrompt一直返回false,除非返回ture,否則這個(gè)頁面通過a標(biāo)簽就無法跳轉(zhuǎn)了...
- 此時(shí)無論怎么點(diǎn)擊一鍵開啟都不會(huì)有效果,那么改成return true試試
- public handlePrompt = (location: Location) => {
- return true;
- };
- 一跳就過去了
問題來了,怎么判斷是否需要跳轉(zhuǎn)呢?
- 參考微信公眾號(hào)編輯器,如果你編輯了內(nèi)容后(跟初始進(jìn)入的數(shù)據(jù)不一致),而且你是通過頁面內(nèi)a標(biāo)簽跳轉(zhuǎn)的,那么就出現(xiàn)彈窗確認(rèn))
- 那么很簡單,我們使用antd的Modal組件,以及l(fā)odash的deepclone(深拷貝)、_.isEqual(value, other)執(zhí)行深比較來確定兩者的值是否相等。
❝ 注意: isEqual這個(gè)方法支持比較 arrays, array buffers, booleans, date objects, error objects, maps, numbers, Object objects, regexes, sets, strings, symbols, 以及 typed arrays. Object 對(duì)象值比較自身的屬性,不包括繼承的和可枚舉的屬性。不支持函數(shù)和DOM節(jié)點(diǎn)比較。 ❞
實(shí)現(xiàn)思路講解
- 組件初始化時(shí)候,深拷貝一份表單數(shù)據(jù)存入組件中
- 當(dāng)用戶通過a標(biāo)簽離開頁面時(shí),觸發(fā)handlePrompt方法,存儲(chǔ)離開的目的url,此時(shí)使用isEqual比較當(dāng)前的數(shù)據(jù)和組件初始化的表單數(shù)據(jù)是否一致,如果不一致則出現(xiàn)彈窗,讓用戶選擇是否離開
- 代碼實(shí)現(xiàn):
- // 處理自定義離開彈窗
- handlePrompt =(location )=>{
- // 如果當(dāng)前的保存為false,則彈窗提醒用戶進(jìn)行保存操作
- if (!this.isSave) {
- this.showModalSave(location);
- return false;
- }
- return true;
- }
- // 展示離開的提示的彈窗
- showModalSave = location => {
- this.setState({
- modalVisible: true,
- location,
- });
- }
- // 點(diǎn)擊確認(rèn),進(jìn)行頁面保存操作,和保存成功后路由的跳轉(zhuǎn)
- handleSaveAuto = () => {
- const { location } = this.state;
- const { history } = this.props;
- this.isSave = true;
- this.setState({
- modalVisible: false,
- });
- //進(jìn)行保存操作的處理,這里可以換成自己點(diǎn)擊確認(rèn)后需要做的操作
- this.handleSavePaper('save','exit',location.pathname)
- }
- 離開邏輯
- // 取消是的路由跳轉(zhuǎn)
- gotoNewUrl(url){
- const {dispatch,history } = this.props
- dispatch(routerRedux.push({
- pathname:url,
- }));
- }
- // 點(diǎn)擊取消關(guān)閉彈窗
- closeModalSave=()=>{
- const { location } = this.state;
- const {dispatch,history } = this.props
- this.isSave = true;
- this.setState({
- modalVisible: false,
- },()=>{
- this.gotoNewUrl(location.pathname)
- });
- }
- html結(jié)構(gòu)
- <Prompt message={this.handlePrompt}/>
- <Modal
- title="溫馨提示"
- visible={this.state.modalVisible}
- closable={false}
- centered
- onCancel={this.closeModalSave}
- footer={null}
- >
- <p>即將離開當(dāng)前頁面,是否保存當(dāng)前修改?</p>
- <div style={{textAlign:'right'}}>
- <Button type='primary' onClick={this.handleSaveAuto}>保存</Button>
- <Button style={{marginLeft:'20px'}} onClick={this.closeModalSave}>取消</Button>
- </div>
- </Modal>