Skip to content

Commit 18de329

Browse files
committed
refactor: refactor VueSkipTo component
1 parent 9734526 commit 18de329

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

src/skip-to.vue renamed to src/VueSkipTo.vue

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,26 +23,28 @@ export default {
2323
this.init()
2424
},
2525
26+
beforeDestroy () {
27+
window.removeEventListener('hashchange', this.handleFocusElement, false)
28+
},
29+
2630
methods: {
2731
init () {
28-
window.addEventListener('hashchange', () => {
29-
this.focusElement(location.hash.substring(1))
30-
}, false)
32+
window.addEventListener('hashchange', this.handleFocusElement, false)
33+
if (location.hash && location.hash.substring(1)) this.handleFocusElement()
34+
},
3135
32-
if (location.hash && location.hash.substring(1)) {
33-
this.focusElement(location.hash.substring(1))
34-
}
36+
handleFocusElement () {
37+
this.focusElement(location.hash.substring(1))
3538
},
3639
3740
focusElement (id) {
3841
if (!id) return
3942
const element = window.document.getElementById(id)
40-
if (element) {
41-
if (!/^(a|select|input|button|textarea)/i.test(element.tagName.toLowerCase())) {
42-
element.setAttribute('tabindex', -1)
43-
}
44-
element.focus()
43+
if (!element) return
44+
if (!/^(a|select|input|button|textarea)/i.test(element.tagName.toLowerCase())) {
45+
element.setAttribute('tabindex', -1)
4546
}
47+
element.focus()
4648
}
4749
}
4850
}

src/index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import VueSkipTo from './skip-to.vue'
1+
import VueSkipTo from './VueSkipTo.vue'
22

33
export default function install (Vue) {
4+
if (install.installed) return
5+
install.installed = true
46
Vue.component('VueSkipTo', VueSkipTo)
57
}
68

0 commit comments

Comments
 (0)