I am trying to implement a ‘application/ld+json’ in the header whenever I use the Item collapse component. To not have dublicate script tags in the head I am trying to inject the json data from a plugin whenever I need it. I am using nuxt3 and vue3 js in my setup. I am pretty sure the call for the addLdScript is wrong I am just not sure how to properly do that.
That’s my code:
export default defineNuxtPlugin((nuxtApp) => {
const metaLdScripts = []
nuxtApp.addLdScript = (script) => metaLdScripts.push(script)
const attachLdScripts = () => {
const head = document.getElementsByTagName('head')[0]
metaLdScripts.forEach((script) => {
const scriptTag = document.createElement('script')
scriptTag.type = 'application/ld+json'
scriptTag.text = JSON.stringify(script)
head.appendChild(scriptTag)
})
}
nuxtApp.hook('render:route', (url, result, context) => {
attachLdScripts()
})
})
<template>
<div v-editable="blok" class="c-item c-item-collapse">
<button @click="toggleCollapse" class="c-item-collapse__header">
<div class="c-item-collapse__title">
<ui-headline size="0" :tagName="blok.title_headline">
{{ blok.title }}
</ui-headline>
</div>
<div class="c-item-collapse__actions">
<ui-icon v-if="!isCollapsed" icon="circle-minus" />
<ui-icon v-else icon="circle-plus" />
</div>
</button>
<div></div>
<div v-show="!isCollapsed" class="c-item-collapse__content">
<StoryblokComponent
v-for="blok in blok.items"
:key="blok._uid"
:blok="blok"
/>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, inject } from 'vue'
const isCollapsed = ref(true)
function toggleCollapse() {
isCollapsed.value = !isCollapsed.value
}
const { blok } = defineProps({ blok: Object })
const $addLdScript = inject('addLdScript')
onMounted(() => {
$addLdScript({
'@context': 'https://schema.org',
'@type': 'FAQPage',
mainEntity: [
{
'@type': 'Question',
name: blok.title,
acceptedAnswer: {
'@type': 'Answer',
text: blok.items.map(
(item) => item.body?.content[0]?.content[0]?.text
),
},
},
],
})
})
</script>
<style lang="scss">
.c-item-collapse {
@apply p-8 bg-white rounded-xl md:rounded;
.ui-section--bg-white & {
// box-shadow: 0px 0px 25px 0px #22222214;
@apply bg-gray-light;
}
&__header {
@apply flex justify-between items-center text-graphite w-full;
}
&__actions {
@apply flex items-center;
}
&__title {
@apply font-black font-barlow text-left text-sm md:text-base;
}
&__content {
@apply pt-4 text-xs md:text-base;
}
}
.c-item-collapse + .c-item-collapse {
@apply mt-2 md:mt-4;
}
</style>
Error: $addLdScript is not a function.
Any hints are much appreciated!