feat(bridge): add support for useNuxt2Meta in plugins (#3187)

This commit is contained in:
Daniel Roe 2022-02-15 09:50:40 +00:00 committed by GitHub
parent 42373e060d
commit d046c9620b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,6 +4,7 @@ import type { MetaInfo } from 'vue-meta'
import type VueRouter from 'vue-router'
import type { Route } from 'vue-router'
import type { RuntimeConfig } from '@nuxt/schema'
import defu from 'defu'
import { useNuxtApp } from './app'
export { useLazyAsyncData } from './asyncData'
@ -90,8 +91,15 @@ type AugmentedComponent = CombinedVueInstance<Vue, object, object, object, Recor
$metaInfo?: MetaInfo
}
/** internal */
function metaInfoFromOptions (metaOptions: Reffed<MetaInfo> | (() => Reffed<MetaInfo>)) {
return metaOptions instanceof Function ? metaOptions : () => metaOptions
}
export const useNuxt2Meta = (metaOptions: Reffed<MetaInfo> | (() => Reffed<MetaInfo>)) => {
const vm = getCurrentInstance()!.proxy as AugmentedComponent
let vm: AugmentedComponent | null = null
try {
vm = getCurrentInstance()!.proxy as AugmentedComponent
const meta = vm.$meta()
const $root = vm.$root
@ -109,8 +117,7 @@ export const useNuxt2Meta = (metaOptions: Reffed<MetaInfo> | (() => Reffed<MetaI
// @ts-ignore
vm.$options.head = vm.$options.head || {}
const metaSource = metaOptions instanceof Function ? metaOptions : () => metaOptions
const unwatch = watch(metaSource, (metaInfo: MetaInfo) => {
const unwatch = watch(metaInfoFromOptions(metaOptions), (metaInfo: MetaInfo) => {
vm.$metaInfo = {
...vm.$metaInfo || {},
...unwrap(metaInfo)
@ -121,4 +128,16 @@ export const useNuxt2Meta = (metaOptions: Reffed<MetaInfo> | (() => Reffed<MetaI
}, { immediate: true, deep: true })
onBeforeUnmount(unwatch)
} catch {
const app = (useNuxtApp().nuxt2Context as any).app
if (typeof app.head === 'function') {
const originalHead = app.head
app.head = function () {
const head = originalHead.call(this) || {}
return defu(unwrap(metaInfoFromOptions(metaOptions)), head)
}
} else {
app.head = defu(unwrap(metaInfoFromOptions(metaOptions)), app.head)
}
}
}