Skip to content

Instantly share code, notes, and snippets.

@uzbekdev1
Forked from rvanzon/nuxt.config.js
Created March 30, 2021 17:39
Show Gist options
  • Save uzbekdev1/e17cc4e332eb0c8a2fe8d86133c2152e to your computer and use it in GitHub Desktop.
Save uzbekdev1/e17cc4e332eb0c8a2fe8d86133c2152e to your computer and use it in GitHub Desktop.
A way to use vue-chartjs as a plugin of Nuxt.js

(WARNING: THIS IS OUTDATED, DON'T USE AS IS! INSTEAD CHECK OUT THE COMMENTS AT THE BOTTOM)

And check out: https://github.com/nuxt/nuxt.js/tree/dev/examples/vue-chartjs

How does this work

  1. Create a custom plugin and put it in plugins (plugins_vue-chartjs.js).
  2. Add the plugin to nuxt.config.js and set ssr to false to prevent the server to initialize it.
  3. You can use the component now just like other Vue-components. The only problem is that you get errors because the DOM-tree is out of sync (because the server misses the component)
  4. As mounted() is only called by the client (browser) we're using this to render the component only in the browser. Add showLine: false to data (so the server will not render it) and turn it to true in mounted().
  5. Use v-if to render the component. Now it won't be rendered on the server side, but it will show up in de browser.

This way also works with other Vue.js plugins

Used in this example:
npm install vue-chartjs --save
npm install chart.js --save

// just an example. A cleaner way is to wrap the showLine-stuff in a dedicated component
<template>
<div>
<my-line v-if="showLine" :data="lineData" :options="options">
</div>
</template>
<script>
export default {
data () {
return {
showLine: false
}
},
mounted () {
this.showLine = true // showLine will only be set to true on the client. This keeps the DOM-tree in sync.
},
asyncData () {
const lineData = {} // some data
const options = {} // some options
return { lineData, options }
}
}
</script>
...
/*
** Build configuration
*/
plugins: [
{ src: '~/plugins/vue-chart.js', mode: 'client' },
],
...
import Vue from 'vue'
import { Line } from 'vue-chartjs'
Vue.component('my-line', Line.extend({
props: ['data', 'options'],
mounted () {
this.renderChart(this.data, this.options)
}
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment