Skip to content

Commit

Permalink
feat(useTitle): add useTitle
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 19, 2020
1 parent 689d0c6 commit 527846c
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 0 deletions.
20 changes: 20 additions & 0 deletions docs/useTitle.md
@@ -0,0 +1,20 @@
# ``useTitle``
---

Composition Function that sets title of the page

## Usage
---

```vue
<script>
import { useTitle } from 'composition-fn'
export default {
setup () {
// 返回值为 setTitle 函数可用来更新 title
useTitle('title')
}
}
<script>
```

1 change: 1 addition & 0 deletions src/index.ts
@@ -0,0 +1 @@
export * from './useTitle'
18 changes: 18 additions & 0 deletions src/useTitle.ts
@@ -0,0 +1,18 @@
import { ref, onUnmounted, watchEffect } from 'vue'

export function useTitle(title: string, restoreOnUnMount = false) {
const cache = document.title
const titleRef = ref(title)
watchEffect(() => {
document.title = titleRef.value
})
if (restoreOnUnMount) {
onUnmounted(() => {
document.title = cache
})
}
const setTitle = (title: string) => {
titleRef.value = title
}
return setTitle
}
54 changes: 54 additions & 0 deletions tests/useTitle.test.ts
@@ -0,0 +1,54 @@
import { defineComponent, nextTick } from 'vue'
import { mount, VueWrapper } from '@vue/test-utils'
import { useTitle } from '../src/useTitle'

describe('test useTitle when restoreOnUnMount is true', () => {
let wrapper: VueWrapper<any>, setTitle: (title: string) => void
beforeEach(() => {
const comp = defineComponent({
template: '<div>test</div>',
setup () {
setTitle = useTitle('test', true)
}
})
document.title = 'init'
wrapper = mount(comp)
})

test('useTitle should be defined', () => {
expect(useTitle).toBeDefined()
})

test('document.title should be test after component mounted', () => {
expect(document.title).toBe('test')
})

test('document.title should change after invoking setTitle', (done) => {
setTitle('change')
nextTick(() => {
expect(document.title).toBe('change')
done()
})
})

test('document.title should be reset to init after component unmounted', () => {
wrapper.unmount()
expect(document.title).toBe('init')
})
})

describe('test useTitle when passing one parameter', () => {
test('document.title should not be reset to init when component is unmounted', () => {
const comp = defineComponent({
template: '<div>test</div>',
setup () {
useTitle('test')
}
})
document.title = 'init'
const wrapper = mount(comp)
expect(document.title).toBe('test')
wrapper.unmount()
expect(document.title).toBe('test')
})
})

0 comments on commit 527846c

Please sign in to comment.