Created
March 22, 2025 10:05
-
-
Save atomjoy/0181223123531c9a3feb2a63817e72a9 to your computer and use it in GitHub Desktop.
Add page structured data in json in Vue 3.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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