Vue 3 - Svgator player is always undefined.
P粉478835592
P粉478835592 2023-07-28 08:44:31
0
1
452
<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粉478835592
P粉478835592

reply all(1)
P粉455093123

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> 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!