-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
lmhcoding
committed
Sep 20, 2020
1 parent
190dbcc
commit 8c8d3f7
Showing
3 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | ||
}) | ||
}) |