We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
今天在群里看到有妹子提出一个问题,vue-router hash模式路由变化无法触发hashchange事件,应该怎么处理?
答: 其实是因为vue-router内部是用 replaceState/pushState 触发hash的变化,而replaceState和pushState的调用并不会触发hashchange事件或者popstate事件。
replaceState/pushState
ps: hashchange事件需要挂载在window才能触发
思绪良久,苦无破敌之计,谷歌一下,发现有大佬用自定义事件可以解决,因为无法触发,只能在replaceState/pushState的调用时添加自定义事件,通过自定义事件去触发。
构造函数Event
语法
const event = new Event(typeArg, eventInit);
触发自定义事件
// 创建一个支持冒泡且不能被取消的look事件 var ev = new Event("look", {"bubbles":true, "cancelable":false}); document.dispatchEvent(ev) // 事件可以在任何元素触发,不仅仅是document myDiv.dispatchEvent(ev)
// 往pushState里添加自定义事件 function newEvent (type) { const fn= history[type] return function () { const returnValue = fn.apply(this, arguments) const e = new Event(type) e.arguments = arguments // 触发自定义事件 window.dispatchEvent(e) return returnValue } } history.pushState = newEvent('pushState') history.replaceState= newEvent('replaceState') // 监听自定义事件 window.addEventListener('pushState', function (e) { console.log('pushState') }) window.addEventListener('replaceState', function (e) { console.log('replaceState') })
在单页应用中,如何优雅的监听url的变化 Event
The text was updated successfully, but these errors were encountered:
你好,我想知道这一段代码的含义是啥? const returnValue = fn.apply(this, arguments)
const returnValue = fn.apply(this, arguments)
Sorry, something went wrong.
执行history[type]这个函数(也就是fn),有返回值就返回
No branches or pull requests
开头
今天在群里看到有妹子提出一个问题,vue-router hash模式路由变化无法触发hashchange事件,应该怎么处理?
答: 其实是因为vue-router内部是用
replaceState/pushState
触发hash的变化,而replaceState和pushState的调用并不会触发hashchange事件或者popstate事件。思绪良久,苦无破敌之计,谷歌一下,发现有大佬用自定义事件可以解决,因为无法触发,只能在replaceState/pushState的调用时添加自定义事件,通过自定义事件去触发。
Event
构造函数Event
语法
"bubbles",可选,Boolean类型,默认值为 false,表示该事件是否冒泡。
"cancelable",可选,Boolean类型,默认值为 false, 表示该事件能否被取消。
"composed",可选,Boolean类型,默认值为 false,指示事件是否会在影子DOM
dispatchEvent
触发自定义事件
自定义事件
参考
在单页应用中,如何优雅的监听url的变化
Event
The text was updated successfully, but these errors were encountered: