Nuxtjs与scrollmagic一起使用时出现“window is not defined”错误。

3

我希望在nuxtjs中使用scrollmagic。

我通过npm安装了scrollmagic。

npm install scrollmagic

在我的nuxt.config.js文件中,我添加了以下内容:
build: {
    vendor: ['scrollmagic']
},

在我的pages/index.vue文件中,我只是简单地导入它。

import ScrollMagic from 'scrollmagic'

但这只会导致以下错误

[vue-router] 无法解析异步组件默认值: ReferenceError: window is not defined [vue-router] 路由导航期间未捕获的错误: ReferenceError: window is not defined at C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:37:2 at C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:22:20 at Object. (C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:27:2)

我该如何修复这个问题?

1个回答

12

将一个名为"scrollmagic.js"的文件添加到您的插件文件夹中,并将以下代码粘贴到其中:

plugins/scrollmagic.js

import ScrollMagic from 'scrollmagic'
将插件添加到您的 nuxt.config.js 文件中。

nuxt.config.js
module.exports = {
  build: {
    vendor: ['scrollmagic']
  },
  plugins: [
    // ssr: false to only include it on client-side
    { src: '~/plugins/scrollmagic.js', ssr: false }
  ]
}

使用它与if (process.client) {}一起

页面或组件

<script>
let scrollmagic
if (process.client) {
  scrollmagic = require('scrollmagic')
// use scrollmagic
}
</script>

欲了解更多信息,请参阅有关此主题的优秀文档:https://nuxtjs.org/guide/plugins/


这解决了关于“window未定义”的问题,但现在我遇到了这个错误ERROR calling setTween() due to missing Plugin 'animation.gsap'. Please make sure to include plugins/animation.gsap.js。还没有找到NuxtJS的解决方案... 你有什么想法吗? - ZeferiniX
你是否把一个名为“animation.gsap.js”的文件添加到了插件文件夹中?如果是的话,请确保没有打错字。 - Schwesi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接