首页 > 解决方案 > 如何在 nuxt 项目中添加 ScrollMagic?

问题描述

我正在尝试在我的 Nuxt 项目中添加 ScollMagic,我关注了这篇文章:https ://nuxtjs.org/guide/plugins 并且我在 nuxt.config.js 中添加了 ScrollMagic.js,我遇到了这个问题:ReferenceError 窗口是没有定义的。

module.exports = {
 plugins: [
    { src: '~plugins/ScrollMagic', mode: 'client' }
  ],
}

Then I've added this snippet in my component:
import ScrollMagic from 'scrollmagic'

我还有这个问题...

即使像这样覆盖它:

if (process.client) {
  Vue.use(ScrollMagic)
}

标签: vue.jsnuxt.jsscrollmagic

解决方案


我知道这个问题有点老了,但也许有人会发现我的 solotion 很有帮助。

编辑:另外,这样你可以将任何插件注册到 nuxt :)。

所以我做了什么:

1. npm i scrollmagic

  1. 转到 nuxt.config.js 并将以下内容添加到您的插件部分:

{ src: '~/plugins/ScrollMagic.js', mode: 'client' }

这将确保 scrollmagic 仅包含在客户端中。这可以防止window undefined错误。

  1. 转到plugins文件夹,或将其放入根文件夹并创建一个名为ScrollMagic.js. 在这里添加以下内容:
import Vue from 'vue';
import * as ScrollMagic from 'scrollmagic';

Object.defineProperty(Vue.prototype, '$scrollmagic', { value: ScrollMagic });

此代码段将使变量 $scrollmagic 在每个组件/页面中可用。你可以打电话this.$scrollmagic来使用它。例如const controller = new this.$scrollmagic.Controller();

希望这对任何人都有帮助。


推荐阅读