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,35 +91,53 @@ 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
const meta = vm.$meta()
const $root = vm.$root
let vm: AugmentedComponent | null = null
try {
vm = getCurrentInstance()!.proxy as AugmentedComponent
const meta = vm.$meta()
const $root = vm.$root
if (!vm._vueMeta) {
vm._vueMeta = true
if (!vm._vueMeta) {
vm._vueMeta = true
let parent = vm.$parent as AugmentedComponent
while (parent && parent !== $root) {
if (parent._vueMeta === undefined) {
parent._vueMeta = false
let parent = vm.$parent as AugmentedComponent
while (parent && parent !== $root) {
if (parent._vueMeta === undefined) {
parent._vueMeta = false
}
parent = parent.$parent
}
parent = parent.$parent
}
// @ts-ignore
vm.$options.head = vm.$options.head || {}
const unwatch = watch(metaInfoFromOptions(metaOptions), (metaInfo: MetaInfo) => {
vm.$metaInfo = {
...vm.$metaInfo || {},
...unwrap(metaInfo)
}
if (process.client) {
meta.refresh()
}
}, { 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)
}
}
// @ts-ignore
vm.$options.head = vm.$options.head || {}
const metaSource = metaOptions instanceof Function ? metaOptions : () => metaOptions
const unwatch = watch(metaSource, (metaInfo: MetaInfo) => {
vm.$metaInfo = {
...vm.$metaInfo || {},
...unwrap(metaInfo)
}
if (process.client) {
meta.refresh()
}
}, { immediate: true, deep: true })
onBeforeUnmount(unwatch)
}