尝试在 nuxt 项目中安装外部 javascript 库 (choreographer-js),但不起作用

问题描述

我对 vue.js 和 nuxt.js 比较陌生。我正在尝试在我的 nuxt.js 项目中安装和使用外部 javascript 库。我只是想测试一下这个功能https://christinecha.github.io/choreographer-js/examples/one.html

图书馆: https://github.com/christinecha/choreographer-js

我已经在我的依赖项中安装了: npm install --save choreographer-js

这是我到目前为止所做的:

插件文件夹中 choreographer.client.js

const Choreographer = require('choreographer-js')

nuxt.config.js

plugins: [{ src: '~/plugins/choreographer.client.js' }],

index.vue

<template>
  <div class="container">
    <p>Animating based on scroll location.</p>
    <div id="Box"></div>
  </div>
</template>

<script>
export default {
  let choreographer = new Choreographer({
  animations: [
    {
      range: [-1,1000],selector: '#Box',type: 'scale',style: 'opacity',from: 0,to: 1
    }
  ]
})

window.addEventListener('scroll',() => {
  choreographer.runAnimationsAt(window.pageYOffset)
})
}
</script>

<style>
p {
  position: fixed;
  top: 100px;
  font-size: 11px;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  font-family: 'Arial',sans-serif;
  color: white;
  text-align: center;
  width: 100%;
  z-index: 1;
}

#Box {
  margin: 0 0;
  width: 100%;
  height: 500vh;
  background: black;
  opacity: 0.2;
}
</style>

错误消息终端:Terminal-screenshot

解决方法

首先,您要导出具有属性而不是函数体的对象 (export default { ... })。所以像 let choreographer = ... 这样的语句在语法上不起作用。这就是导致您出错的原因。

相反,在 Vue 生命周期钩子中运行该代码。例如:


<script>
export default {
  // this is shorthand for mounted: function mounted () {
  mounted () {
    let choreographer = new Choreographer({
      animations: [
        {
          range: [-1,1000],selector: '#box',type: 'scale',style: 'opacity',from: 0,to: 1
        }
      ]
    })

    window.addEventListener('scroll',() => {
      choreographer.runAnimationsAt(window.pageYOffset)
    })
  }
}
</script>

第二个问题,您无疑知道,因为您创建了一个只能运行客户端 (~/plugins/choreographer.client.js) 的插件,您只需要注意运行用于浏览器中的浏览器(这意味着您不能假设编排器实例是在服务器端定义的)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...