Home  >  Q&A  >  body text

Vue 3 - Svgator player is always undefined.

<p>Currently, I used SVGator to create an SVG animation. <br />I imported it as a resource into my application and tried to get it running. </p><p>I followed the instructions in this document and successfully implemented it. </p><p>However, since I may need to create a large number of animations, I tried to make it more general. </p><p><br /></p> <pre class="brush:js;toolbar:false;"><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> </pre> <p>This is a complete Vue application containing the same code. </p><p>Why is svg?.svgatorPlayer always null? </p><p><strong></strong></p>
P粉478835592P粉478835592464 days ago499

reply all(1)I'll reply

  • P粉455093123

    P粉4550931232023-07-29 00:05:50

    So, to answer your question, it looks like your firstChild is an HTMLElement containing any svgatorPlayer.

    You are using ?raw to process the svg as a string.

    To fix this problem you must follow this answer.

    Secondly, reading the documentation provided, you are not using JavaScript with the svg, but rather placing it as a string. That's why your svgatorPlayer is equal to null, because it doesn't exist when the js is not executed. One solution is to execute the svg in v-html, but be aware of the problem of XSS injection.

    ##

    <template>
      <div v-html="exampleSvg"></div>
      <Component :is="animatedSvg" />
    </template> 

    reply
    0
  • Cancelreply