1
votes

I'm trying to add Chartist library to existing NuxtJs project. Below is a configuration I have:

> 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>

On the first attempt to open page nuxt returns an error:

ReferenceError: window is not defined

After page reload it always returns:

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

However no errors raising and chart is visible if open page from another page through VueRouter.

But here is another problem - chart is not shown as expected: enter image description here

I guess this is due to lack of related css styles.

I would appreciate for any advise:
- how to correctly include Chartist (or any other vanilla js library)
- how to attach css related to js library

p.s. I know there are different chartist vue components, but I want to understand how to work with vanilla js libraries in nuxt.

1

1 Answers

1
votes

Here below the only working variant which found for the moment:

<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>