目前,我使用SVGator制作了一个SVG动画。
我将其作为资源导入到我的应用程序中,并尝试让它运行起来。
我按照这份文档的说明成功实现了它的运行。
但是,由于我可能需要创建大量的动画,我尝试将其更加通用化。
<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>
这是一个完整的Vue应用程序,包含相同的代码。
为什么svg?.svgatorPlayer始终为null?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
所以,为了回答你的问题,看起来你的firstChild是一个包含任何svgatorPlayer的HTMLElement。
你正在使用?raw将svg作为字符串处理。
要修复这个问题,你必须按照这个答案进行操作。
其次,阅读所提供的文档后,你没有使用JavaScript与svg一起使用,而是将其作为字符串放置。这就是为什么你的svgatorPlayer等于null,因为在js未执行时它不存在。一个解决方案是将svg放在v-html中执行,但要注意XSS注入的问题。
<template> <div v-html="exampleSvg"></div> <Component :is="animatedSvg" /> </template>