Skip to content

Instantly share code, notes, and snippets.

@amirulasyraf88
Forked from rvanzon/nuxt.config.js
Created July 18, 2019 09:58
Show Gist options
  • Save amirulasyraf88/80d4307798358bf949d85d7986ab40e4 to your computer and use it in GitHub Desktop.
Save amirulasyraf88/80d4307798358bf949d85d7986ab40e4 to your computer and use it in GitHub Desktop.
A way to use vue-chartjs as a plugin of Nuxt.js

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-chartjs.js', ssr: false },
],
...
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