Search code examples
vue.jshighchartsvuejs3nuxt.js

How to include highcharts in Nuxt 3.7.0?


How can I include this combination graph https://www.highcharts.com/demo/highcharts/combo-dual-axes chart in my nuxt vue application ? I followed this https://www.npmjs.com/package/highcharts-vue docs, but could not get how to integrate this package with my nuxt vue application. In the docs it is mentioned that for vue 3 I should use this

// for Vue 3 app.use(HighchartsVue)

But no where in my nuxt application I have something like app.use().

I am getting this : Failed to resolve component: highcharts

This is my index.vue file

<template>
<highcharts :constructorType="'stockChart'" 
:options="testOptions"></highcharts>
</template>

<script>
  import { Chart } from 'highcharts-vue';
  import Highcharts from 'highcharts-vue'

  export default {
  name: 'Home',

  data() {
    return {
        testOptions: {
            series: [{
                data: [1, 2, 3] // sample data
            }]
        },
      }
    },
  }

</script>

<style></style>

Can someone please tell me how can I properly import this highcharts-vue packages and get the desired graph I need ?


Solution

  • If you'd like to use the officially supported highcharts-vue package in your Nuxt 3 project, here are some steps to make it work (Highcharts is a client-side library so it requires an additional setup so that Nuxt knows to handle it on the client-side only):

    1. Create a highcharts.client.js file in the /plugins directory for Nuxt:
    import { defineNuxtPlugin } from '#app';
    import Highcharts from 'highcharts';
    import HighchartsVue from 'highcharts-vue';
    import stockInit from 'highcharts/modules/stock';
    
    export default defineNuxtPlugin({
       name: 'highcharts-vue',
       parallel: true,
       setup (nuxtApp) {
           if (typeof Highcharts === 'object') {
               stockInit(Highcharts);
           }
           nuxtApp.vueApp.use(HighchartsVue);
       }
    });
    

    In this file you can set up Highcharts with the modules that you'd like to use.

    1. Register the plugin in your nuxt.config.ts file:
    export default defineNuxtConfig({
        ... the rest of your config
        plugins: [
            // Ensure this runs on client side only
            { src: '~/plugins/highcharts.client.js', mode: 'client' }
        ]
    });
    
    1. Use the highcharts component in your .vue files:
    <script setup>
    import { ref } from 'vue';
    
    const options = ref({
        title: {
            text: 'My chart'
        },
        series: [{
            data: [1, 2, 3]
        }]
    });
    </script>
    
    <template>
      <div>
        <highcharts :options="options" />
      </div>
    </template>
    

    Please let me know if that works for you.