Skip to content

Commit

Permalink
feat: add useHash
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 20, 2020
1 parent 190dbcc commit 8c8d3f7
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export * from './useLocalStorage'
export * from './useStorage'
export * from './useLifecycles'
export * from './useInterval'
export * from './useHash'
21 changes: 21 additions & 0 deletions src/useHash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ref } from 'vue'
import { useEvent } from './useEvent'

export function useHash() {
const state = ref(window.location.hash)

const setHash = (hash: string) => {
if (hash !== state.value) {
window.location.hash = hash
}
}

const onHashChange = () => {
state.value = window.location.hash
}
useEvent('hashchange', onHashChange)
return {
state,
setHash
}
}
38 changes: 38 additions & 0 deletions tests/useHash.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Ref } from 'vue'
import { useHash } from '../src/useHash'

let hash = '#test'
const mockLocation = {}
Object.defineProperty(mockLocation, 'hash', {
get () {
return hash
},
set (val) {
hash = val
window.dispatchEvent(new HashChangeEvent('hashchange'))
}
})
Object.defineProperty(window, 'location', {
value: mockLocation
})

describe('test useHash', () => {
let state: Ref<string>
let setHash: (hash: string) => void
beforeEach(() => {
const res = useHash()
state = res.state
setHash = res.setHash
})
test('initial state should be test', () => {
expect(state.value).toBe('#test')
})
test('hash should change after invoking setHash with new hash', () => {
setHash('new')
expect(window.location.hash).toBe('new')
})
test('state.value should change after changing hash with window.location.hash', () => {
window.location.hash = 'new'
expect(state.value).toBe('new')
})
})

0 comments on commit 8c8d3f7

Please sign in to comment.