Skip to content

Commit

Permalink
feat(useTitle): new option observe to watch title changes (#483)
Browse files Browse the repository at this point in the history
* feat(useTitle): Use MutationObserver for react on changes

* fix: typecheck

* feat:  provide an `disableObserver` option

* fix: rename `disableObserver` to `enableObserver`

That's more cleared

* chore: update

Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
cawa-93 and antfu committed May 7, 2021
1 parent 0aeba76 commit 7ab3fe6
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion packages/core/useTitle/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import { isString, MaybeRef } from '@vueuse/shared'
import { ref, watch } from 'vue-demi'
import { ConfigurableDocument, defaultDocument } from '../_configurable'
import { useMutationObserver } from '../useMutationObserver'

export interface UseTitleOptions extends ConfigurableDocument {
/**
* Observe `document.title` changes using MutationObserve
*
* @default false
*/
observe?: boolean
}

/**
* Reactive document title.
Expand All @@ -11,8 +21,12 @@ import { ConfigurableDocument, defaultDocument } from '../_configurable'
*/
export function useTitle(
newTitle: MaybeRef<string | null | undefined> = null,
{ document = defaultDocument }: ConfigurableDocument = {},
options: UseTitleOptions = {},
) {
const {
document = defaultDocument,
observe = false,
} = options
const title = ref(newTitle ?? document?.title ?? null)

watch(
Expand All @@ -24,5 +38,16 @@ export function useTitle(
{ immediate: true },
)

if (observe && document) {
useMutationObserver(
document.head?.querySelector('title'),
() => {
if (document && document.title !== title.value)
title.value = document.title
},
{ childList: true },
)
}

return title
}

0 comments on commit 7ab3fe6

Please sign in to comment.