首页  >  问答  >  正文

Vue 3 - Svgator播放器始终为undefined。

<p>目前,我使用SVGator制作了一个SVG动画。<br />我将其作为资源导入到我的应用程序中,并尝试让它运行起来。</p><p>我按照这份文档的说明成功实现了它的运行。</p><p>但是,由于我可能需要创建大量的动画,我尝试将其更加通用化。</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>这是一个完整的Vue应用程序,包含相同的代码。</p><p>为什么svg?.svgatorPlayer始终为null?</p><p><strong></strong></p>
P粉478835592P粉478835592448 天前484

全部回复(1)我来回复

  • P粉455093123

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

    所以,为了回答你的问题,看起来你的firstChild是一个包含任何svgatorPlayer的HTMLElement。

    你正在使用?raw将svg作为字符串处理。

    要修复这个问题,你必须按照这个答案进行操作。

    其次,阅读所提供的文档后,你没有使用JavaScript与svg一起使用,而是将其作为字符串放置。这就是为什么你的svgatorPlayer等于null,因为在js未执行时它不存在。一个解决方案是将svg放在v-html中执行,但要注意XSS注入的问题。

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

    回复
    0
  • 取消回复