onbeforeunload
,MDN的说明是:当浏览器窗口关闭或者刷新时,会触发beforeunload事件。当前页面不会直接关闭,可以点击确定按钮关闭或刷新,也可以取消关闭或刷新。
beforeunload
事件`<script type="text/javascript"> window.onbeforeunload = function () { return "Leave this page?"; } </script>`
"xxx.ooo.com"
会出现
`import { Prompt } from 'dva/router'; .... render(){ return <Prompt message={this.handlePrompt} /> }`
`public handlePrompt = (location: Location) => { return false; };`
`public handlePrompt = (location: Location) => { return true; };`
❝注意: isEqual这个方法支持比较 arrays, array buffers, booleans, date objects, error objects, maps, numbers, Object objects, regexes, sets, strings, symbols, 以及 typed arrays. Object 对象值比较自身的属性,不包括继承的和可枚举的属性。 不支持函数和DOM节点比较。
❞
`// 处理自定义离开弹窗 handlePrompt =(location )=>{ // 如果当前的保存为false,则弹窗提醒用户进行保存操作 if (!this.isSave) { this.showModalSave(location); return false; } return true; } // 展示离开的提示的弹窗 showModalSave = location => { this.setState({ modalVisible: true, location, }); } // 点击确认,进行页面保存操作,和保存成功后路由的跳转 handleSaveAuto = () => { const { location } = this.state; const { history } = this.props; this.isSave = true; this.setState({ modalVisible: false, }); //进行保存操作的处理,这里可以换成自己点击确认后需要做的操作 this.handleSavePaper('save','exit',location.pathname) }`
`// 取消是的路由跳转 gotoNewUrl(url){ const {dispatch,history } = this.props dispatch(routerRedux.push({ pathname:url, })); } // 点击取消关闭弹窗 closeModalSave=()=>{ const { location } = this.state; const {dispatch,history } = this.props this.isSave = true; this.setState({ modalVisible: false, },()=>{ this.gotoNewUrl(location.pathname) }); }`
`<Prompt message={this.handlePrompt}/> <Modal title="温馨提示" visible={this.state.modalVisible} closable={false} centered onCancel={this.closeModalSave} footer={null} > <p>即将离开当前页面,是否保存当前修改?</p> <div style={{textAlign:'right'}}> <Button type='primary' onClick={this.handleSaveAuto}>保存</Button> <Button style={{marginLeft:'20px'}} onClick={this.closeModalSave}>取消</Button> </div> </Modal>`
在看
,关注一波公众号:[前端巅峰
]前端生活社区
:https://qianduan.life