update
This commit is contained in:
@@ -1,19 +1,37 @@
|
||||
import { watchEffect, toValue, type MaybeRefOrGetter } from 'vue';
|
||||
import { watch, toValue, type MaybeRefOrGetter } from 'vue';
|
||||
import useDJSSRContext from "@/useDJSSRContext.ts";
|
||||
import { h } from "@/util.ts";
|
||||
|
||||
export default function useHead(params: {
|
||||
title: MaybeRefOrGetter<string>,
|
||||
metatags?: MaybeRefOrGetter<Array<{ name: string, content: string }>>
|
||||
}) {
|
||||
const context = useDJSSRContext();
|
||||
|
||||
if (context) {
|
||||
context.head.title = params.title;
|
||||
context.head.metatags = params.metatags ?? [];
|
||||
} else {
|
||||
watchEffect(() => {
|
||||
const newTitle = toValue(params.title);
|
||||
watch([() => toValue(params.title), () => toValue(params.metatags) ?? []], ([newTitle, newMetatags]) => {
|
||||
if (newTitle) {
|
||||
document.title = newTitle;
|
||||
}
|
||||
});
|
||||
const currMetatags = document.head.querySelectorAll('meta');
|
||||
const existing = new Set<string>();
|
||||
for (const currMetatag of currMetatags) {
|
||||
const match = newMetatags.find(_ => _.name === currMetatag.name);
|
||||
if (!match) {
|
||||
currMetatag.remove();
|
||||
} else {
|
||||
existing.add(match.name);
|
||||
currMetatag.content = match.content;
|
||||
}
|
||||
}
|
||||
for (const newMetatag of newMetatags) {
|
||||
if (!existing.has(newMetatag.name)) {
|
||||
document.head.appendChild(h('meta', newMetatag));
|
||||
}
|
||||
}
|
||||
}, { immediate: true });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user