以ember框架为例:

封装的service:

import Service from '@ember/service'
import { inject as service } from "@ember/service"
import fetch from 'fetch'
import { tracked } from '@glimmer/tracking'
import { action } from '@ember/object'


export default class BrowserEventsServiceService extends Service {
	@tracked param
	@tracked routeName
	@service router

	// 注册浏览器监听事件
	registerListener(route) {
		let that = this
		$(function(){
			that.param = this.location.href.split('?')[1]
			that.routeName = `/${route}?`
			//回退
			if (window.history && window.history.pushState) {
				history.pushState(null, null, document.URL);
				
				window.addEventListener("popstate", that.popstateFun, false);
			}
			//关闭&刷新(页面有变动或距上次刷新间隔超过5s时生效)
			window.onbeforeunload=function(e){
				return false
			}
			//文档加载完成后立即触发
			window.onload = function(){
				// 刷新回到指定页面
                that.router.transitionTo( `${that.routeName}${that.param}` )
			}	
		});
	}

	@action
	popstateFun() {
		let that = this
		let sel = confirm("您还没有保存更改,确认返回吗?")
		if(sel) {
			window.removeEventListener("popstate", that.popstateFun);
			that.router.transitionTo( `${that.routeName}${that.param}` )
		} else {
			history.pushState(null, null, document.URL);
		}
	}
	//清除浏览器监听事件
	clearListener() {
		window.onbeforeunload = undefined
		window.removeEventListener("popstate",this.popstateFun)
	}
}

用法:

    @service browserEventsService;
	
	beforeModel() {
		// 1. 清除所有页面监听事件,防止重复调用
		this.browserEventsService.clearListener()
		// 2. 注册监听事件,参数为要跳转页面的router
		this.browserEventsService.registerListener('flow')
    }

vue用法同上。

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐