Skip to content

Instantly share code, notes, and snippets.

@package71
Last active February 13, 2022 08:41
Show Gist options
  • Save package71/fd0282cf14b2da0a75024a867d4d2976 to your computer and use it in GitHub Desktop.
Save package71/fd0282cf14b2da0a75024a867d4d2976 to your computer and use it in GitHub Desktop.
Nuxt vue-chartjs
import Vue from "vue";
import {Bar, Line, mixins} from "vue-chartjs";
Vue.component("chartline", {
extends: Line,
mixins: [mixins.reactiveProp],
props: ["options"],
mounted() {
const max = Math.max(...this.chartData.datasets[0].data);
this.renderChart(this.chartData, {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
min: 0,
max: (max / 100) * 120,
}
}
]
},
legend: {display: false}
});
}
});
Vue.component("chart-bar", {
extends: Bar,
props: ["data", "options", "styles"],
mounted() {
console.log(this);
this.renderChart(this.data, this.options);
}
});

Nuxt config plugins

{src: "~/plugins/vue-chartjs.js", ssr: false}

example store

export const state = () => ({
  errorData: "",
  load: false,
  info: {
    labels: [],
    data: [],
  }
});

export const getters = {
  getData: state => state.info,
  getLoad: state => state.load,
  getError: state => state.errorData
};

export const mutations = {
  changeData: (state, data) => {
    if (data) {
      state.info.labels = data.map(r => r[0]);
      state.info.data = data.map(r => r[1]);
    }
  },
  changeError: (state, error) => (state.error = error),
  changeLoad: (state, load) => (state.load = load)
};

export const actions = {
  async getStatisticClient({commit}) {
    commit("changeLoad", false);
    const res = await this.app.$rest.api(
      "admin/visits/statistic/get",
      this.app.context.query
    );
    commit("changeLoad", true);
    let main = res.data.visitorStatistics;
    if (main.length === 0) return commit("changeData", false);
    let arr = main.map(el => {
      return [el.date.slice(0, 10), parseInt(el.total_count)];
    });
    commit("changeData", arr);
  }
};

Template:

<chartline
        :options="{responsive: true, maintainAspectRatio: false}"
        :chart-data="chart"
        :height="260"
      />
return {
        labels: this.dat.labels,
        datasets: [
          {
            backgroundColor: "rgb(122, 190, 253)",
            borderColor: "rgba(24, 143, 255, 1)",
            pointBackgroundColor: "rgba(24, 143, 255, 1)",
            borderWidth: 3,
            label: "Visits",
            pointHoverBorderWidth: 2,
            pointBorderWidth: 0,
            lineTension: 0.3,
            data: this.dat.data
          }
        ]
      };
@kossa
Copy link

kossa commented Feb 13, 2022

@kossa
Copy link

kossa commented Feb 13, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment