Vue 3 - Svgator播放器始终为undefined。
P粉478835592
P粉478835592 2023-07-28 08:44:31
[Vue.js讨论组]
<p>目前,我使用SVGator制作了一个SVG动画。<br />我将其作为资源导入到我的应用程序中,并尝试让它运行起来。</p><p>我按照这份文档的说明成功实现了它的运行。</p><p>但是,由于我可能需要创建大量的动画,我尝试将其更加通用化。</p><p><br /></p> <pre class="brush:js;toolbar:false;">&lt;script setup lang="ts"&gt; import { ref, defineComponent, h, component, watch } from 'vue'; import exampleSvg from '@assets/example.svg?raw'; interface IComponentProperties { svg: string; } const componentProperties = withDefaults(defineProps&lt;IComponentProperties&gt;(), { svg: () =&gt; exampleSvg, }); const element = ref&lt;HTMLElement&gt;(); 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( () =&gt; element.value, () =&gt; { runAnimation(); }, { immediate: true, } ); &lt;/script&gt; &lt;template&gt; &lt;Component :is="animatedSvg" /&gt; &lt;/template&gt; </pre> <p>这是一个完整的Vue应用程序,包含相同的代码。</p><p>为什么svg?.svgatorPlayer始终为null?</p><p><strong></strong></p>
P粉478835592
P粉478835592

全部回复(1)
P粉455093123

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

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

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

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

<template>
  <div v-html="exampleSvg"></div>
  <Component :is="animatedSvg" />
</template> 
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号