在Nuxt.js 3中使用GSAP SplitText报错的解决求助
解决Nuxt3 + @hypernym/nuxt-gsap使用SplitText报错问题
错误原因
你碰到的Cannot read properties of undefined (reading 'SplitText')问题,核心有两点:
- SplitText是GSAP的付费专属插件(仅Club GreenSock成员可获取),
@hypernym/nuxt-gsap默认不会自动集成它 - 代码里用
this.SplitText是错误写法——Nuxt3的Composition API中,this不指向Vue实例,不能这么调用
解决步骤
1. 确保已获取并安装SplitText
如果你是Club GreenSock成员,先通过官方渠道获取SplitText文件,或使用授权npm源安装:
npm install @gsap/SplitText
2. 在Nuxt中配置注册SplitText
修改nuxt.config.ts,在gsap配置中添加插件注册:
export default defineNuxtConfig({ modules: ['@hypernym/nuxt-gsap'], gsap: { plugins: { register: [ { name: 'SplitText', from: '@gsap/SplitText', register: 'SplitText' } ] } } })
3. 修正组件代码
把原有代码改成以下形式,从$gsap中正确调用SplitText:
<script setup> const { $gsap } = useNuxtApp(); onMounted(() => { const childSplit = new $gsap.SplitText(".text-animation", { type: "lines" }); console.log(childSplit); }); </script>
额外提醒
- 未购买Club GreenSock授权的话,SplitText无法正常使用,需先获取授权
- 确保页面中存在
.text-animation类的元素,否则SplitText会找不到目标元素
内容的提问来源于stack exchange,提问作者Kuzey Demirel
相关产品推荐
相关产品推荐

