Currently I've made an svg animation using SVGator.
I've imported it as an asset to my application and I was trying to make it run.
I've made it work following this Docs
But, as I may need to create a bunch of animations, I've tried to make this more generic.
<script setup lang="ts">
import { ref, defineComponent, h, component, watch } from 'vue';
import exampleSvg from '@assets/example.svg?raw';
interface IComponentProperties {
svg: string;
}
const componentProperties = withDefaults(defineProps<IComponentProperties>(), {
svg: () => exampleSvg,
});
const element = ref<HTMLElement>();
const animatedSvg = defineComponent({
render() {
return h('svg', { innerHTML: componentProperties.svg, ref: element });
},
});
function runAnimation() {
if (!element.value) return;
const { firstChild } = element.value;
const svg = firstChild as any;
svg?.svgatorPlayer?.play();
}
watch(
() => element.value,
() => {
runAnimation();
},
{
immediate: true,
}
);
</script>
<template>
<Component :is="animatedSvg" />
</template>
Here is a full vue app with the same code
Why svg?.svgatorPlayer is always null?
So to answer your question, it seems your
firstChildis an HTMLElement with inside anysvgatorPlayerprovided.You are treating the svg as a string using the
?raw.For fixing this you must follow this answer.
Second of all after reading the documentation provided, you are not using the
Javascriptwith thesvgyou are putting it as a string this is why yoursvgatorPlayerequals to null because it doesn't exist while the js is not executed a solution will be to put thesvgin av-htmlto execute it but be carefull with the XSS injections.