Skip to content

Instantly share code, notes, and snippets.

@atomjoy
Created March 22, 2025 10:05
Show Gist options
  • Save atomjoy/0181223123531c9a3feb2a63817e72a9 to your computer and use it in GitHub Desktop.
Save atomjoy/0181223123531c9a3feb2a63817e72a9 to your computer and use it in GitHub Desktop.
Add page structured data in json in Vue 3.
<template></template>
<script setup>
import { watch } from 'vue';
const props = defineProps({
json: {
type: [Array, Object],
default: [],
},
});
const head = document.querySelector('head');
const el = document.createElement('script');
watch(
() => props.json,
function (n, o) {
try {
if (props.json) {
el.setAttribute('type', 'application/ld+json');
el.setAttribute('id', 'structured-data');
el.innerText = JSON.stringify(JSON.parse(props.json));
head.appendChild(el);
}
} catch (err) {}
}
);
function getSchemaObject(id = '#structured-data') {
let el = document.querySelector(id);
let obj = JSON.parse(el.innerText);
return obj;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment