Skip to content
This repository has been archived by the owner on Dec 5, 2024. It is now read-only.

fix: 🐛 Support reactive useMeta in layouts #65

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
{
"name": "Daniel Roe <daniel@roe.dev>",
"url": "https://github.com/danielroe"
},
{
"name": "Jacob Andersson <jacob@sigbit.se>",
"url": "https://github.com/miii"
}
],
"keywords": [
Expand Down
33 changes: 26 additions & 7 deletions src/meta.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import defu from 'defu'
import { getCurrentInstance, toRefs, Ref, reactive } from '@vue/composition-api'
import { getCurrentInstance, toRefs, Ref, watch } from '@vue/composition-api'
import Vue from 'vue'

import type { MetaInfo } from 'vue-meta'
import type { UnwrapRef } from '@vue/composition-api/dist/reactivity'
Expand Down Expand Up @@ -40,14 +41,25 @@ export function createEmptyMeta(): MetaInfoMapper<Required<MetaInfo>> {
}
}

function objAssignReactive<T extends object>(target: T, ...mergeObj: any[]) {
mergeObj.forEach(mObj => {
Object.keys(mObj).forEach(k => Vue.set(target, k, mObj[k]))
})
return target
}

export const getHeadOptions = (options: any) => {
const _head: ReactiveHead = reactive<MetaInfo>({})
const _head: ReactiveHead = Vue.observable<MetaInfo>({})
if (!(options.head instanceof Function)) {
Object.assign(_head, options.head)
objAssignReactive(_head, options.head)
}
const head =
options.head instanceof Function
? () => defu(_head, options.head())
? () =>
objAssignReactive(
_head,
defu(Object.assign({}, _head), options.head())
)
: () => _head
return { _head, head }
}
Expand All @@ -56,6 +68,8 @@ type ToRefs<T extends Record<string, any>> = {
[P in keyof T]: Ref<T[P]>
}

let metaRefsWatcher: any

/**
* `useMeta` lets you interact directly with [`head()` properties](https://nuxtjs.org/api/pages-head/) in `setup`. **Make sure you set `head: {}` in your component options.**
* @example
Expand Down Expand Up @@ -83,7 +97,12 @@ export const useMeta = <T extends MetaInfo>(init?: T) => {

const { _head } = vm.$options as { _head: ReactiveHead }

Object.assign(_head, createEmptyMeta())
Object.assign(_head, init || {})
return toRefs(_head) as ToRefs<ReturnType<typeof createEmptyMeta> & T>
objAssignReactive(_head, createEmptyMeta(), init || {})
const refs = toRefs(_head) as ToRefs<ReturnType<typeof createEmptyMeta> & T>

if (process.client && !metaRefsWatcher) {
metaRefsWatcher = watch(Object.values(refs), () => vm.$meta().refresh())
}

return refs
}