【问题标题】:Adding vanilla js library to Nuxt将 vanilla js 库添加到 Nuxt
【发布时间】:2019-03-16 21:26:50
【问题描述】:

我正在尝试将 Chartist 库添加到现有的 NuxtJs 项目中。 以下是我的配置:

> npm i chartist

~plugins/chartist.js:

import Chartist from 'chartist'
export default Chartist

nuxt.config.js:

module.exports = {
    plugins: [{src:'~plugins/chartist.js', ssr:false}],
    build: {
        vendor: ['chartist']
    }
}

index.vue:

<template>
  <div>
    <div class="ct-chart"></div>
  </div>
</template>

<script>

import Chartist from 'chartist'

export default {
  mounted(){

    var chart=new Chartist.Line('.ct-chart', {
        labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
        series: [
          [12, 9, 7, 8, 5],
          [2, 1, 3.5, 7, 3],
          [1, 3, 4, 5, 6]
        ]
      }, {
        fullWidth: true,
        chartPadding: {
          right: 40
        }
      });

  }
}
</script>

第一次尝试打开页面时 nuxt 返回错误:

ReferenceError: window is not defined

页面重新加载后总是返回:

Error: render function or template not defined in component: anonymous

但是,如果通过 VueRouter 从另一个页面打开页面,则不会引发错误并且图表是可见的。

但这是另一个问题 - 图表未按预期显示:

我猜这是因为缺少相关的 css 样式。

如果您有任何建议,我将不胜感激:
- 如何正确包含 Chartist(或任何其他 vanilla js 库)
- 如何附加js库相关的css

附言我知道有不同的 chartist vue 组件,但我想了解如何在 nuxt 中使用 vanilla js 库。

【问题讨论】:

    标签: javascript vue.js ecmascript-6 nuxt.js


    【解决方案1】:

    目前发现的唯一工作变体如下:

    <script>
    
    import 'chartist/dist/chartist.min.css'
    
    export default {
     data() {
      return {
       chartist: null
      }
     },
     mounted() {
    
      this.chartist = require('chartist')
      var z = new this.chartist.Line('.ct-chart', {
       labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
       series: [
        [12, 9, 7, 8, 5],
        [2, 1, 3.5, 7, 3],
        [1, 3, 4, 5, 6]
       ]
      }, {
       fullWidth: true,
       chartPadding: {
        right: 40
       }
      });
    
     }
    } 
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2018-04-29
      • 2017-09-26
      • 2018-12-16
      • 2020-04-19
      • 2020-06-29
      • 2011-07-07
      相关资源
      最近更新 更多