如何在Vue中为多个元素使用refs?含GSAP动画实现方案
Vue中用refs批量操作DOM元素并应用GSAP动画
你当前的代码确实只会对单个元素生效——因为Vue里,多个非v-for循环内的元素使用相同ref时,$refs只会保留最后一个匹配的元素,所以GSAP只作用在了一个元素上。
下面是两种解决方案,优先推荐你要求的循环方式:
方案一:用v-for重构模板(优先循环方式)
通过v-for渲染重复的section和p元素,此时Vue会自动将相同的ref收集为数组,直接就能批量操作。
完整代码:
<template> <section :ref="`section${item.type.charAt(0).toUpperCase() + item.type.slice(1)}`" v-for="item in contentSections" :key="item.type" > <p ref="pre">{{ item.text }}</p> </section> </template> <script> import gsap from 'gsap' export default { data() { return { contentSections: [ { type: 'Text', text: 'text' }, { type: 'Image', text: 'some more text' }, { type: 'Audio', text: 'even more' }, { type: 'Video', text: 'text' } ] } }, mounted() { // this.$refs.pre 此时是包含所有p元素的数组,GSAP可直接处理数组 gsap.to(this.$refs.pre, 0.75, { opacity: 0 }) } } </script>
方案二:不使用v-for的替代方案
如果不想重构模板,可以给所有目标p元素添加统一类名,通过类选择器批量获取元素:
修改后的模板:
<template> <section ref="sectionText"> <p ref="pre" class="pre-target">text</p> </section> <section ref="sectionImage"> <p ref="pre" class="pre-target">some more text</p> </section> <section ref="sectionAudio"> <p ref="pre" class="pre-target">even more</p> </section> <section ref="sectionVideo"> <p ref="pre" class="pre-target">text</p> </section> </template>
修改后的脚本:
import gsap from 'gsap' export default { mounted() { // 通过类选择器获取所有目标元素 const elements = document.querySelectorAll('.pre-target') gsap.to(elements, 0.75, { opacity: 0 }) } }
内容的提问来源于stack exchange,提问作者MathAdams
相关产品推荐
相关产品推荐

