Nuxtjs with scrollmagic gives me “window is not defined”

自作多情 提交于 2019-12-24 06:20:42

问题


I want to use scrollmagic with nuxtjs.

I installed scrollmagic via npm.

npm install scrollmagic

In my nuxt.config.js file i added

build: {
    vendor: ['scrollmagic']
},

And in my pages/index.vue file i simply imported it.

import ScrollMagic from 'scrollmagic'

But this results only in this error

[vue-router] Failed to resolve async component default: ReferenceError: window is not defined [vue-router] uncaught error during route navigation: 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)

How can i fix this?


回答1:


Add a file to your plugins folder called "scrollmagic.js" and paste the following code into it:

plugins/scrollmagic.js

import ScrollMagic from 'scrollmagic'

Add the plugin to your nuxt.config.js file

nuxt.config.js

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

Use it with if (process.client) {}

page or component

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

For more information please consult the excellent documentation on this topic: https://nuxtjs.org/guide/plugins/



来源:https://stackoverflow.com/questions/47844836/nuxtjs-with-scrollmagic-gives-me-window-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!