Nuxt.js show window is not defined when load to production - vue.js

I have an application with nuxt.js as a framework and it's running well in development mode. However, when I deployed to the server for production, it's show "window is not defined".
I think it's because highcharts-vue.min.js module not loaded in components so shows this error but I'm not sure about that. I attach some code and screen shoot results after deploying on the server
<template>
<highcharts class="hc" :options="chartOptions" ref="chart">
</highcharts>
</template>
<script>
import {Chart} from 'highcharts-vue'
export default {
name:"ForecastCuaca",
components: {
highcharts: Chart
},
data() {
return {
data_cuaca:[],
chartOptions: {
chart: {
type: 'spline',
backgroundColor: 'transparent',
marginTop:100
},
title: {
text: 'Prakiraan Cuaca Kota Kupang',
style:{
"color": "#ebeefd",
"fontSize": "22px"
}
},
subtitle: {
text: 'Source: openweathermap.org',
style:{
"color": "#ebeefd",
}
},
xAxis: {
categories: ['Tanggal'],
labels:{
style:{
color:"#ebeefd"
}
}
},
yAxis: {
title: {
text: 'Suhu'
},
labels: {
formatter: function () {
return this.value + '°';
},
style:{
color:"#ebeefd"
}
},
style:{
"color": "#ebeefd",
}
},
tooltip: {
formatter: function () {
return 'Suhu : ' + this.y + '° C<br /><b>' + this.x + '</b>';
}
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
series: [{
name: 'Kota Kupang',
marker: {
symbol: 'square'
},
data: [
10
],
style:{
"color": "#ebeefd",
}
}
],
credits:{
enabled:false
}
},
title: '',
}
},
methods:{
generate_data(datax){
const self = this;
self.data_cuaca = datax
self.chartOptions.xAxis.categories = []
self.chartOptions.series[0].data = []
let ganjil = 0;
for (let index = 0; index < self.data_cuaca.length; index++) {
ganjil++;
const element = self.data_cuaca[index];
self.chartOptions.xAxis.categories.push(element.waktu_indonesia)
if (ganjil % 2 == 1) {
const iconx = element.weather[0].icon+'.png';
const data_series = {
y:element.main.temp,
marker: {
symbol: "url(http://openweathermap.org/img/w/"+iconx+")"
}
}
self.chartOptions.series[0].data.push(data_series)
}else{
self.chartOptions.series[0].data.push(element.main.temp)
}
}
}
}
}
</script>

Related

How to remove line over the stroke line in area chart - Apexchart?

How to remove line over the stroke line in area chart - Apexchart. the image
Please help me to fix this!
Here is my code so far
<template>
<div id="chart">
<apexchart
ref="pricesRef"
type="area"
height="150"
:options="options"
:series="series"
></apexchart>
<!-- <button #click="updateSeries">click</button> -->
</div>
</template>
<script>
import { axios } from 'boot/axios';
// import { dates, prices } from 'src/services/area-chart';
import { date } from 'quasar';
function formatNumber2(number, tofix) {
const val = (number / 1).toFixed(tofix).replace(',', ' ');
return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
let sharePrice = [];
const dataSharePrice = [];
export default {
name: 'AreaChart',
data() {
return {
timeInterval: 0,
dataSharePrice: [],
series: [
{
name: 'Share Price',
data: [
// { x: dates[0], y: prices[1] },
// { x: 1602392287529, y: 0.05 },
],
date: [],
},
],
options: {
chart: {
type: 'area',
zoom: {
enabled: false,
},
toolbar: {
show: false,
},
sparkline: {
enabled: true,
},
},
tooltip: {
custom({ series, w, dataPointIndex }) {
const unixTime = w.config.series[0].data[dataPointIndex].x;
const timeStamp = new Date(unixTime * 1000);
const hour = date.formatDate(timeStamp, 'DD MMMM');
return (
`
<div class="arrow_box_tooltip q-pa-md">
<span class="text-h6">
Date: ${hour}</span>
<br />
<span class="text-h6">
Share Price: $${formatNumber2(
series[0][dataPointIndex],
0,
)} USD</span>
</div>
`
);
},
},
noData: {
text: 'Loading...',
},
dataLabels: {
enabled: false,
},
stroke: {
curve: 'smooth',
lineCap: 'butt',
colors: undefined,
width: 2,
},
title: {
text: '',
align: 'left',
},
grid: {
show: false,
},
xaxis: {
type: 'datetime',
},
yaxis: {
opposite: true,
},
legend: {
horizontalAlign: 'left',
},
},
};
},
computed: {},
methods: {
getData() {
axios
.get(
'apiurl',
)
.then((response) => {
// console.log(response.data.prices);
sharePrice = response.data.prices;
})
.catch((err) => {
console.log(err);
});
},
updateSeriesData() {
for (const price of sharePrice) {
const unixTime = price[0];
if (Object.keys(price).length > 0) {
dataSharePrice.push({
x: unixTime,
y: price[1],
});
} else {
dataSharePrice.push({});
console.log('err');
}
// console.log(price[0], price[1]);
}
// console.log(dataSharePrice);
this.series[0].data = dataSharePrice;
this.$refs.pricesRef.updateSeries([
{
data: dataSharePrice,
},
]);
// console.log(this.$refs);
},
// timer() {},
},
mounted() {},
async created() {
await this.getData();
setTimeout(() => {
this.updateSeriesData();
// console.log('done');
}, 3000);
/* ; */
// this.timer();
},
beforeDestroy() {
// clearInterval(this.timer);
},
};
</script>
<style scoped>
/* #chart {
background-color: #18212f;
opacity: 1;
background-size: 7px 7px;
background-image: repeating-linear-gradient(
45deg,
#111726 0,
#111726 0.7000000000000001px,
#18212f 0,
#18212f 50%
);
} */
</style>
You can specify each stroke width separately by passing array
stroke: {
curve: 'smooth',
lineCap: 'butt',
colors: undefined,
width: [2,0],
},

How can I call a method from options of ApexChart with vue.js

I'm new with vue and apex charts, basically what I need is to call a method from the apex chart options, I created a file showing the problem I'm having:
https://jsfiddle.net/wr3uo5va/
I need to call the method currencyValue from chartOptions.dataLabels
dataLabels: {
enabled: true,
offsetX: -25,
formatter: function(val) {
return val + " Reais"; <--- This works
// return this.currencyValue(val) <--- This does not work
},
},
Any suggestion ?
The problem is this inside the formatter callback is the chart instance (not the component instance) because it's declared as a regular function.
The solution is to use an arrow function to bind the component instance as the context:
export default {
methods: {
currencyValue(value) {⋯},
loadChartData() {
⋮
this.chartOptions = {
⋮
dataLabels: {
⋮
// ❌ don't use regular function here
//formatter: function(val) {
// return this.currencyValue(val)
//},
// ✅
formatter: (val) => {
return this.currencyValue(val)
},
},
}
}
}
}
updated fiddle
You can put chartOptions in methods instead of in data.
Below is working code
const currencyValue = (val) => {
return "R$" + val;
}
new Vue({
el: "#app",
data() {
return {
series: [450, 300, 500]
}
},
methods: {
chartOptions() {
return {
labels: ['Paid', 'Pending', 'Rejected'],
plotOptions: {
radialBar: {
size: 165,
offsetY: 30,
hollow: {
size: '20%'
},
track: {
background: "#ebebeb",
strokeWidth: '100%',
margin: 15,
},
dataLabels: {
show: true,
name: {
fontSize: '18px',
},
value: {
fontSize: '16px',
color: "#636a71",
offsetY: 11
},
total: {
show: true,
label: 'Total',
formatter: function() {
return 42459
}
}
}
},
},
responsive: [{
breakpoint: 576,
options: {
plotOptions: {
radialBar: {
size: 150,
hollow: {
size: '20%'
},
track: {
background: "#ebebeb",
strokeWidth: '100%',
margin: 15,
},
}
}
}
}],
colors: ['#7961F9', '#FF9F43', '#EA5455'],
fill: {
type: 'gradient',
gradient: {
// enabled: true,
shade: 'dark',
type: 'vertical',
shadeIntensity: 0.5,
gradientToColors: ['#9c8cfc', '#FFC085', '#f29292'],
inverseColors: false,
opacityFrom: 1,
opacityTo: 1,
stops: [0, 100]
},
},
stroke: {
lineCap: 'round'
},
chart: {
dropShadow: {
enabled: true,
blur: 3,
left: 1,
top: 1,
opacity: 0.1
},
},
tooltip: {
x: {
formatter: function (val) {
return val;
},
},
y: {
formatter: function (val) {
return currencyValue(val);
},
},
},
}
}
},
components: {
VueApexCharts
}
})
Methods can't be called in data or computed, they can be called in methods
One thing to be modified in html is below
<vue-apex-charts
type="donut"
:options="chartOptions()"
:series="series">
</vue-apex-charts>

How to correctly pass array with data to a chart from the VueApexCharts library in vue3?

I am writing a small covid project and trying to plot confirmed infection data using ApexCharts, but the graph is not showing. I enter the data from vuex in two tables. The data is valid however it comes from api and sa in the proxy object. What am I doing wrong? (I am using ApexCharts because vue Chartjs is not compatible with vue 3).
<template>
<apexchart width="500" type="bar" :options="options" :series="series"></apexchart>
</template>
<script>
import VueApexCharts from "vue3-apexcharts";
export default {
components: {
apexchart: VueApexCharts,
},
data(){
return {
series: [],
options: {
chart: {
type: "bar",
height: 400,
stacked: true
},
plotOptions: {
bar: {
horizontal: false
}
},
dataLabels: {
enabled: false
},
tooltip: {
shared: true,
followCursor: true
},
stroke: {
width: 1,
colors: ["#fff"]
},
fill: {
opacity: 1
},
legend: {
position: "top",
horizontalAlign: "center",
offsetX: 40
},
colors: ["rgb(95, 193, 215)", "rgb(226, 37, 43)", "rgb(94, 181, 89)"]
}
};
},
computed: {
getDate(){
return this.$store.getters['chart/getDate'];
},
getConfirmed(){
return this.$store.getters['chart/getConfirmed'];
}
},
methods: {
fillDate(){
this.options = {
xaxis: {
categories: this.getDate
}
}
this.series = [
{
name: 'Confirmed',
data: this.getConfirmed
}
];
}
},
async mounted() {
await this.fillDate();
}
}
The data from the vuex store are two arrays.
Proxy
[[Handler]]: Object
[[Target]]: Array(45)
[[IsRevoked]]: false
Instead of using mounted hook and method try to watch the computed properties then update the data based on that ones:
computed: {
getDate(){
return this.$store.getters['chart/getDate'];
},
getConfirmed(){
return this.$store.getters['chart/getConfirmed'];
}
},
watch:{
getDate:{
handler(newVal){
this.options = {
xaxis: {
categories: this.getDate
}
},
deep:true
},
getConfirmed:{
handler(newVal){
this.series = [
{
name: 'Confirmed',
data: this.getConfirmed
}
];
},
deep:true
}
}

Error in mounted hook: "TypeError: Cannot read property 'type' of null"

I am using echarts to draw a Heatmap
But giving me error!!
Error in mounted hook: "TypeError: Cannot read property 'type' of null"
mounted() {
this.initChart()
},
I am using the json data from here:
https://www.echartsjs.com/data/asset/data/hangzhou-tracks.json
Just took 1 data from the above link.
<template>
<div
:id="id"
:class="className"
:style="{height:height,width:width}"
/>
</template>
<script>
import echarts from 'echarts'
import resize from '../mixins/resize'
export default {
mixins: [resize],
props: {
className: {
type: String,
default: 'chart'
},
id: {
type: String,
default: 'newCustomerForecastChart'
},
width: {
type: String,
default: '200px'
},
height: {
type: String,
default: '200px'
}
},
data() {
return {
chart: null,
dataArr: [
{
"coord":
[
120.14322240845,
30.236064370321
],
"elevation": 21
},
{
"coord":
[
120.14280555506,
30.23633761213
],
"elevation": 5
}
]
}
},
mounted() {
this.initChart()
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose()
this.chart = null
},
methods: {
initChart() {
var points = [
{
"coord":
[
120.14322240845,
30.236064370321
],
"elevation": 21
},
{
"coord":
[
120.14280555506,
30.23633761213
],
"elevation": 5
}
]
this.chart = echarts.init(document.getElementById(this.id))
var colors = ['#5793f3', '#d14a61', '#675bba'];
this.chart.setOption({
animation: false,
bmap: {
center: [120.13066322374, 30.240018034923],
zoom: 14,
roam: true
},
visualMap: {
show: false,
top: 'top',
min: 0,
max: 5,
seriesIndex: 0,
calculable: true,
inRange: {
color: ['blue', 'blue', 'green', 'yellow', 'red']
}
},
series: [{
type: 'heatmap',
coordinateSystem: 'bmap',
data: points,
pointSize: 5,
blurSize: 6
}]
});
var bmap = myChart.getModel().getComponent('bmap').getBMap();
bmap.addControl(new BMap.MapTypeControl());
}
}
}
</script>
What is the problem actually?
should use
import * as echarts from 'echarts'
imstead of
import echarts from 'echarts'

Trying to refresh label when click on it. Cannot read property '_meta' of undefined"

I'm trying that the percentages in a pie-chart refresh when clicking in a legend to hide data.
So far, I can display the chart with percentages, but they don't change if I hide one of the legends.
This is the chart: initial chart
This is how looks after the click: after click
We expect that instead 55.6%, it shows 100%.
This is my code so far:
<script>
import {Pie} from "vue-chartjs";
import ChartJsPluginDataLabels from 'chartjs-plugin-datalabels';
export default {
extends: Pie,
ChartJsPluginDataLabels,
props: {
data: Array,
bg: Array,
labels: Array
},
data() {
return {
}
},
computed: {
chartData() {
return this.data
},
bgData() {
return this.bg
},
total() {
return this.data.reduce((a, b) => a + (b || 0), 0)
}
},
methods: {
renderPieChart() {
this.renderChart({
labels: this.labels,
datasets: [
{
label: "Data One",
backgroundColor: this.bgData,
data: this.chartData,
hoverBackgroundColor: "#f78733"
}
]
}, {
responsive: true,
plugins: {
datalabels: {
formatter: (value) => {
let sum = this
.$refs.canvas.getContext('2d').dataset._meta[1].total; //use this.total to fix percentages
let percentage = (value * 100 / sum).toFixed(1) + "%";
return percentage;
},
color: '#fff'
}
}
})
console.log()
},
updateSelected(point, event) {
const item = event[0]
this.selected = {
index: item._index,
value: this
.chartData
.datasets[0]
.data[item._index]
}
}
},
watch: {
bg: function () {
this.renderPieChart();
},
data: function () {
this.renderPieChart();
}
},
}
</script>
In order to obtain the expected result, you should define plugins.datalabels.formatter as follows:
formatter: (value, context) => {
return (value * 100 / context.dataset._meta[0].total).toFixed(1) + "%";
}
new Chart(document.getElementById("myChart"), {
type: "pie",
data: {
labels: ['Savings', 'House'],
datasets: [{
label: "Data One",
backgroundColor: ['#4e9258', '#64e986'],
data: [9, 7],
hoverBackgroundColor: "#f78733"
}]
},
options: {
plugins: {
datalabels: {
formatter: (value, context) => {
return (value * 100 / context.dataset._meta[0].total).toFixed(1) + "%";
},
color: '#fff'
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<canvas id="myChart" height="100"></canvas>