google visualization-Click event on barchart isStacked: true - django-templates

I'm trying to display the total value of a barchart where 'isStacked: true' on a <span> located on top of the chart when I click on a bar.
My reference to explore the capability of google.visualization.events.addListener started here.
When I click the a bar I recieved this error:
Uncaught TypeError: Cannot read property 'row' of undefined
or when I change the row to column
Uncaught TypeError: Cannot read property 'column' of undefined
Any pointers is really appreciated.
Here's my django template:
<script type="text/javascript">
$(document).ready(function(){
{% for staff_name, staff_id in params.items %}
$.ajax({
url: "{% url user_kpi %}",
data: { user_stat: {{staff_name}} },
success: function(responseData) {
if (typeof responseData=="object") {
var data = new google.visualization.arrayToDataTable([
['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'],
['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ],
['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']]);
google.setOnLoadCallback(drawVisualization(data, {{staff_name}}));
}
}
});
{% endfor %}
});
var wrapper;
function drawVisualization(xdata, id) {
// Create and draw the visualization.
var visual = 'visualization-'+id.toString();
//chart = new google.visualization.BarChart(document.getElementById(visual));
wrapper = new google.visualization.ChartWrapper({
chartType: 'BarChart',
dataTable: xdata,
options: {
width:600, height:140,
vAxis: {title: null, maxValue: 3500},
hAxis: {title: null},
animation: {easing: 'in'},
axisTitlesPosition: "out",
chartArea:{left:0,top:0, right:0, width:"100%",height:"100%"},
focusTarget: "category",
fontSize: 12,
fontName: "Tahoma",
legend: {position: 'none'},
series: [{color: 'black', visibleInLegend: false}, {}, {},
{color: 'red', visibleInLegend: false}],
isStacked: true,
backgroundColor: '#eee',
},
containerId: visual
});
google.visualization.events.addListener(wrapper, 'ready', function() {
// grab a few details before redirecting
google.visualization.events.addListener(wrapper.getChart(), 'select', function() {
chartObject = wrapper.getChart();
// checking value upon mousehover
alert(xdata.getValue(chartObject.getSelection()[0].row, 0));
//alert(xdata.getValue(chartObject.getSelection()[0].column, 0));
});
});
wrapper.draw();
}
Update: As explain by asgallant.
<script type="text/javascript">
function init () {
{% for staff_name, staff_id in params.items %}
$.ajax({
url: "{% url user_kpi %}",
data: { user_stat: {{staff_name}} },
success: function(responseData) {
if (typeof responseData=="object") {
var data = new google.visualization.arrayToDataTable([
['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'],
['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ],
['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']
]);
drawVisualization(data, {{staff_name}});
}
}
});
{% endfor %}
}
google.load('visualization', '1', {packages:['corechart'], callback: init});
function drawVisualization(xdata, id) {
// Create and draw the visualization.
var visual = 'visualization-'+id.toString(),
//chart = new google.visualization.BarChart(document.getElementById(visual));
wrapper = new google.visualization.ChartWrapper({
chartType: 'BarChart',
dataTable: xdata,
options: {
width:600, height:140,
vAxis: {title: null, maxValue: 3500},
hAxis: {title: null},
animation: {easing: 'in'},
axisTitlesPosition: "out",
chartArea:{left:0,top:0, right:0, width:"100%",height:"100%"},
focusTarget: "category",
fontSize: 12,
fontName: "Tahoma",
legend: {position: 'none'},
//orientation: "vertical"
series: [{color: 'black', visibleInLegend: false}, {}, {},
{color: 'red', visibleInLegend: false}],
isStacked: true,
backgroundColor: '#eee',
},
containerId: visual
});
google.visualization.events.addListener(wrapper, 'ready', function() {
var chart = wrapper.getChart();
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection();
if (selection.length) {
// the user selected a bar
alert(xdata.getValue(selection[0].row, 0));
//alert(selection.length);
}
else {
alert('no selection');// the user deselected a bar
}
});
});
wrapper.draw();
}
Error:
Uncaught Error: Invalid row index undefined. Should be in the range [0-7].
Corrrected by asgallant
Turning this line alert(xdata.getValue(selection.row, 0)); into alert(xdata.getValue(selection[0].row, 0));

First, you AJAX calls should be made inside a callback from the google loader, not from a document ready handler (this guarantees that the the Visualization API is available when you try to use API components):
function init () {
{% for staff_name, staff_id in params.items %}
$.ajax({
url: "{% url user_kpi %}",
data: { user_stat: {{staff_name}} },
success: function(responseData) {
if (typeof responseData=="object") {
var data = new google.visualization.arrayToDataTable([
['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'],
['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ],
['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']
]);
drawVisualization(data, {{staff_name}});
}
}
});
{% endfor %}
}
google.load('visualization', '1', {packages:['corechart'], callback: init});
Then, in your drawVisualization function, you have a couple of problems: to start with, wrapper is a global object, so it gets overwritten every time you call drawVisualization; this is the primary cause of your issue, as the "select" event fires for one chart, but wrapper refers to the last chart drawn, not the chart clicked on (and thus, the wrapper.getChart().getSelection() call returns an empty array, element 0 of an empty array is undefined, and undefined does not have a row or column property). You need to make wrapper local to the drawVisualization function instead of global. Delete this line:
var wrapper;
and add var to the beginning of this line:
wrapper = new google.visualization.ChartWrapper({
Then you need to adjust the event handler to test for the length of the selection array, as the user can click a bar twice, which selects and then deselects the bar, resulting in an empty array, and you would get the same error. The event handler needs to look like this:
google.visualization.events.addListener(wrapper, 'ready', function() {
var chart = wrapper.getChart();
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection();
if (selection.length) {
// the user selected a bar
alert(xdata.getValue(selection[0].row, 0));
}
else {
// the user deselected a bar
}
});
});

Related

ApexCharts y: 0 -> Cannot read properties of undefined

I'm using ApexCharts with vue3 (Composition API). I try to set the series dynamically via a reactive variable. Everything works fine until a dataset is empty - in the sense of its values being 0.
This is the general stub:
<template>
...
<apexchart width="100%" height="400" type="bar" :options="orderOptions" :series="orderSeries" ref="orderChart"></apexchart>
...
</template>
<script setup>
...
const orderSeries = ref([
{
name: 'Orders',
data: []
}
]);
const orderOptions = ref({
xaxis: {
type: 'datetime'
},
yaxis: {
min: 0,
labels: {
formatter: val => val.toFixed(0)
}
},
dataLabels: {
enabled: false
},
markers: {
size: 7,
hover: {
size: 10
}
},
plotOptions: {
bar: {
borderRadius: 4,
borderRadiusApplication: 'end',
columnWidth: '90%'
}
},
title: {
text: 'Orders',
style: {
fontSize: '20px'
}
}
});
...
</script>
This works fine:
orderSeries.value[0].data = [{ x: '2022-03', y: 2 }]
But this:
orderSeries.value[0].data = [{ x: '2022-03', y: 0 }]
Gives me following error:
Uncaught TypeError: Cannot read properties of undefined (reading '0')
at s2 (apexcharts.common.js:10:11991)
...
As long as there is at least one element with a y value different than 0, it will work, but as soon as all y-values are 0, it throws this error.
Can anyone tell me what's wrong with that code?

Can't display data labels in chartJS

I have a web app written with ASP .NET Core, on one of the pages there is a bar chart created using chartJS (it gets data from database). I'm trying to display data values over each bar in the chart. I tried using this plugin, but then my chart doesn't show on the page and I'm getting the following errors: Uncaught ReferenceError: ChartDataLabels is not defined and Uncaught TypeError: Cannot set property 'datalabels' of undefined:
Here is my code for the chart:
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.3.0/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#1.0.0"></script>
<div>
<canvas id="workTSChart_MTK"></canvas>
</div>
<script>
$(document).ready(function () {
$.ajax({
type: "Get",
url: '#Url.Action("OnGetWorkTSData_MTK","home")',
contentType: "application/json",
dataType: "json",
success: function (response) {
var data = response.hrPlan;
var data2 = response.hrReestr;
var data3 = response.hrFact;
console.log("hrPlan=" + response.hrPlan);
console.log("hrSub=" + response.hrReestr);
console.log("hrFact=" + response.hrFact);
var ctx = document.getElementById("workTSChart_MTK");
var workTSChart = new Chart(ctx, {
plugins: [ChartDataLabels],
type: 'bar',
data: {
labels: [
'ООО "МТК"',
],
datasets: [{
label: 'Plan',
data: [response.hrPlan],
backgroundColor: 'rgb(161, 221, 239)',
borderColor: 'rgb(161, 221, 239)',
},
{
label: 'Sub',
data: [data2],
backgroundColor: 'rgb(254, 171, 133)',
borderColor: 'rgb(254, 171, 133)',
},
{
label: 'Fact',
data: [data3],
backgroundColor: 'rgb(127, 137, 138)',
borderColor: 'rgb(127, 137, 138)',
}]
},
options: {
responsive: true,
scales: {
y: {
max: 600000,
min: 500000,
ticks: {
stepSize: 10000,
}
}
},
plugins: {
datalabels: {
color: '#000000',
display: true,
},
legend: {
position: 'top',
},
title: {
display: true,
text: 'Sample title'
}
}
},
});
},
error: function (response) {
alert(response.responseText);
console.log("This is ERROR line");
}
});
});
</script>
What am I missing?
UPDATE:
I've updated my code thanks to #LeeLenalee's advice, but now I'm getting another error message: Uncaught TypeError: Cannot read property 'skip' of undefined
Updated code:
<div>
<canvas id="workTSChart_MTK"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#1.0.0"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "Get",
url: '#Url.Action("OnGetWorkTSData_MTK","home")',
contentType: "application/json",
dataType: "json",
success: function (response) {
var data = response.hrPlan;
var data2 = response.hrReestr;
var data3 = response.hrFact;
console.log("hrPlan=" + response.hrPlan);
console.log("hrSub=" + response.hrReestr);
console.log("hrFact=" + response.hrFact);
var ctx = document.getElementById("workTSChart_MTK");
var workTSChart = new Chart(ctx, {
plugins: [ChartDataLabels],
type: 'bar',
data: {
labels: [
'ООО "МТК"',
],
datasets: [{
label: 'Plan',
data: [response.hrPlan],
backgroundColor: 'rgb(161, 221, 239)',
borderColor: 'rgb(161, 221, 239)',
},
{
label: 'Sub',
data: [data2],
backgroundColor: 'rgb(254, 171, 133)',
borderColor: 'rgb(254, 171, 133)',
},
{
label: 'Hour',
data: [data3],
backgroundColor: 'rgb(127, 137, 138)',
borderColor: 'rgb(127, 137, 138)',
}]
},
options: {
responsive: true,
scales: {
y: {
max: 600000,
min: 500000,
ticks: {
stepSize: 10000,
}
}
},
plugins: {
datalabels: {
color: '#000000',
display: true,
},
legend: {
position: 'top',
},
title: {
display: true,
text: 'Sample title'
}
}
},
});
},
error: function (response) {
alert(response.responseText);
console.log("This is ERROR line");
}
});
});
</script>
UPDATE 2:
As it turns out, there is an updated version of chartjs-plugin-datalabels that is working with ChartJS 3.0, so the solution was to implement latest versions of both as shown below:
<body>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.5.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0/dist/chartjs-plugin-datalabels.min.js"></script>
</body>
As stated in the documentation you will need to have at least Chart.js version 2.7.0 installed, you are currently using 2.3.0.
After that you either have to register the plugin globally by calling Chart.plugins.register(ChartDataLabels); so all the charts have the datalabels or register it locally to the chart you want the labels for as shown in the example below:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
},
plugins: [ChartDataLabels]
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#1.0.0"></script>
</body>

update vue chart-js y axis max value without re rendering entire chart

I am working on a project where I am implementing some charts from the Vue-Chartjs library. I need the Y-axis max value to change everytime the user changes the filters given. I Import an existing barchart from the vue-chartjs library. In the code there is a javascript file that has some defaults already, to set extra options I can use the extraOptions object as a prop to personalize each chart accordingly. Here is the default component:
import { Bar } from 'vue-chartjs'
import { hexToRGB } from "./utils";
import reactiveChartMixin from "./mixins/reactiveChart";
let defaultOptions = {
tooltips: {
tooltipFillColor: "rgba(0,0,0,0.5)",
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
tooltipFontSize: 14,
tooltipFontStyle: "normal",
tooltipFontColor: "#fff",
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
tooltipTitleFontSize: 14,
tooltipTitleFontStyle: "bold",
tooltipTitleFontColor: "#fff",
tooltipYPadding: 6,
tooltipXPadding: 6,
tooltipCaretSize: 8,
tooltipCornerRadius: 6,
tooltipXOffset: 10,
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
fontColor: "#9f9f9f",
fontStyle: "bold",
beginAtZero: true,
display: false,
min: 0,
max: 100
},
gridLines: {
display: false,
drawBorder: false,
}
}],
xAxes: [{
gridLines: {
display: false,
drawBorder: false,
},
}],
}
};
export default {
name: 'BarChart',
extends: Bar,
mixins: [reactiveChartMixin],
props: {
labels: {
type: [Object, Array],
description: 'Chart labels. This is overridden when `data` is provided'
},
datasets: {
type: [Object, Array],
description: 'Chart datasets. This is overridden when `data` is provided'
},
data: {
type: [Object, Array],
description: 'Chart.js chart data (overrides all default data)'
},
color: {
type: String,
description: 'Chart color. This is overridden when `data` is provided'
},
extraOptions: {
type: Object,
description: 'Chart.js options'
},
title: {
type: String,
description: 'Chart title'
},
},
methods: {
assignChartData() {
let { gradientFill } = this.assignChartOptions(defaultOptions);
let color = this.color || this.fallBackColor;
return {
labels: this.labels || [],
datasets: this.datasets ? this.datasets : [{
label: this.title || '',
backgroundColor: gradientFill,
borderColor: color,
pointBorderColor: "#FFF",
pointBackgroundColor: color,
pointBorderWidth: 2,
pointHoverRadius: 4,
pointHoverBorderWidth: 1,
pointRadius: 4,
fill: true,
borderWidth: 1,
data: this.data || []
}]
}
},
assignChartOptions(initialConfig) {
let color = this.color || this.fallBackColor;
const ctx = document.getElementById(this.chartId).getContext('2d');
const gradientFill = ctx.createLinearGradient(0, 170, 0, 50);
gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)");
gradientFill.addColorStop(1, hexToRGB(color, 0.6));
let extraOptions = this.extraOptions || {}
return {
...initialConfig,
...extraOptions,
gradientFill
};
}
},
mounted() {
this.chartData = this.assignChartData({});
this.options = this.assignChartOptions(defaultOptions);
this.renderChart(this.chartData, this.options, this.extraOptions);
}
}
I use this js file to import the bar chart inside a vue component like you see down below.
everytime the input of the form changes i need to re render the chart. I use the onInputChange() method to turn the boolean loaded to false and call the loadData() method.
Inside the loadData() method I make an axios request that gets me the right data every time. I also get the maximum value for my Y axis.
Then in the response I call on updateChart() so that I can update the data and the max value of the chart. then i turn the boolean loaded to true again so that my chart renders accordingly.
The problem with this approach is that the chart disappears completely for a split of a second. Before deciding to change the max Value of the Y axis I was able to update the data of my chart without having to use the v-if="loaded".
I need to find a solution where the chart re renders without it completely disappearing from the page. I know some suggested to use computed variables but i don't fully understand how it is supposed to work. Here is the component minus the form fields.
I guess in it's essence what I want is to update the Y axis max value without having to re render the entire chart.
<template>
<div>
<BarChart v-if="loaded" :labels="chartLabels"
:datasets="datasets"
:height="100"
:extraOptions="extraOptions"
>
</BarChart>
<br>
</div>
</template>
<script>
import BarChart from '../../components/Library/UIComponents/Charts/BarChart'
import Dropdown from "../../components/Library/UIComponents/Dropdown"
import GroupedMultiSelectWidget from "~/components/widgets/GroupedMultiSelectWidget"
import SelectWidget from "../../components/widgets/SelectWidget";
export default{
name: 'PopularChart',
components: {BarChart, Dropdown, SelectWidget, GroupedMultiSelectWidget},
data(){
return {
loaded:true,
form:{
day: 'Today',
workspace:'',
machine_family: [],
duration: [],
user_group: [],
dt_start:'',
dt_end:''
},
url: `/api/data_app/job_count_by_hour/`,
chart_data: [],
days: [ {day:"Today", id:"Today"},
{day:"Monday", id:"0"},
{day:"Tuesday",id:"1"},
{day:"Wednesday",id:"2"},
{day:"Thursday",id:"3"},
{day:"Friday",id:"4"},
{day:"Saturday",id:"5"},
{day:"sunday",id:"6"} ],
chartLabels: ["00u", "1u", "2u", "3u","4u","5u", "6u", "7u", "8u", "9u", "10u", "11u", "12u", "13u", "14u", "15u","16u", "17", "18u","19u","20u","21u","22u","23u"],
datasets: [],
maximumValue: '',
extraOptions:{}
}
},
methods: {
onInputChange() {
this.loaded = false
this.loadData()
},
async loadData() {
await this.$axios.get(`${this.url}?day=${this.form.day}&date_start=${this.form.dt_start}&date_end=${this.form.dt_end}&workspace=${this.form.workspace}&user_group=${this.form.user_group}&machine_family=${this.form.machine_family}`)
.then(response => {
this.updateChart(response.data.results,response.data.maximum)
this.loaded = true
})
},
updateChart(data,maxValue) {
this.datasets = [{
label: ["jobs %"],
backgroundColor:"#f93232",
data: data
},]
this.maximumValue = maxValue
this.extraOptions = {
tooltips: {
callbacks:{
label: function (tooltipItems,){
if (tooltipItems.value > ((50/100) * maxValue)){
return 'busy';
}else if (tooltipItems.value < ((30/ 100) * maxValue) ){
return ' not busy';
}else if ( tooltipItems.value < ((40/ 100) * maxValue )){
return 'kind of busy'
}
}
}
},
scales: {
yAxes: [{
gridLines: {
zeroLineColor: "transparent",
display: false,
drawBorder: false,
},
ticks: {
max: this.maximumValue,
display: true,
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent",
display: false,
drawBorder: false,
},
}],
},
}
},
},
mounted() {
this.loadData()
},
}
</script>
You can bind the chart to a variable in data(), initialize it with some defaults in mounted() and whenever you want to update the chart data, you use the Chart.js API.
An implementation could look something like this:
export default {
data() {
return {
chart: null
};
},
mounted() {
this.chart = new Chart(/* defaults */);
},
methods: {
updateChart(data) {
this.chart.data.datasets = data;
/* rest of the chart updating */
this.chart.update();
}
}
};

VueJS + Chartjs - Chart only renders after code change

I'm using the following tutorial (pull download stats for NPM packages) to build a basis for my charted webapp :
https://hackernoon.com/lets-build-a-web-app-with-vue-chart-js-and-an-api-544eb81c4b44
https://github.com/apertureless/npm-stats
I have extracted the below code from the tutorial and modified it so it does the pure basics. Get data and present data. Specifically from these:
https://github.com/apertureless/npm-stats/blob/develop/src/pages/Start.vue
https://github.com/apertureless/npm-stats/blob/develop/src/components/LineChart.vue
Please note: The code executes the API call and retrieves data no problem. However it will only render that data in the chart if I make a code change. For example changing the color of a line to something else. It seems to only work on the next 'cycle' if that makes sense. Once the data has rendered, if I refresh that page it is once again blank. I suspect it has something to do with the pages timing. However not sure where to begin or what I'm looking for.
App.Vue
<template>
<v-app style="background-color: rgb(228, 228, 228);">
<section class="One">
<v-card class="One" color="rgb(255, 255, 255)" >
<LineChart :chart-data="downloads" :chart-labels="labels"/>
</v-card>
</section>
</v-app>
</template>
<script>
import axios from 'axios';
import LineChart from './components/test3.vue';
export default {
name: 'App',
components: {
LineChart,
},
data () {
return {
package: '',
packageName: '',
loaded: false,
loading: false,
downloads: [],
downloadsYear: [],
downloadsMonth: [],
downloadsWeek: [],
labels: [],
labelsYear: [],
labelsMonth: [],
labelsWeek: [],
showError: false,
showSettings: false,
errorMessage: 'Please enter a package name',
periodStart: '',
periodEnd: new Date(),
rawData: '',
totalDownloads: '',
dailyPng: null,
weeklyPng: null,
monthlyPng: null,
yearlyPng: null
}
},
mounted(){
this.loaded = false
axios.get(`https://api.npmjs.org/downloads/range/2017-01-01:2017-04-19/vue`)
.then(response => {
this.rawData = response.data.downloads
this.downloads = response.data.downloads.map(entry => entry.downloads)
this.labels = response.data.downloads.map(entry => entry.day)
this.packageName = response.data.package
this.totalDownloads = this.downloads.reduce((total, download) => total + download)
this.setURL()
this.groupDataByDate()
this.loaded = true
this.loading = false
})
.catch(err => {
this.errorMessage = err.response.data.error
this.loading = false
})
},
};
</script>
Chart Component:
<script>
import { Line } from 'vue-chartjs'
export default {
extends: Line,
props: {
chartData: {
type: Array,
required: false
},
chartLabels: {
type: Array,
required: true
}
},
data () {
return {
gradient: null,
options: {
showScale: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
},
gridLines: {
display: true,
color: '#EEF0F4',
borderDash: [5, 15]
}
}],
xAxes: [ {
gridLines: {
display: true,
color: '#EEF0F4',
borderDash: [5, 15]
}
}]
},
tooltips: {
backgroundColor: '#4F5565',
titleFontStyle: 'normal',
titleFontSize: 18,
bodyFontFamily: "'Proxima Nova', sans-serif",
cornerRadius: 3,
bodyFontColor: '#20C4C8',
bodyFontSize: 14,
xPadding: 14,
yPadding: 14,
displayColors: false,
mode: 'index',
intersect: false,
callbacks: {
title: tooltipItem => {
return `🗓 ${tooltipItem[0].xLabel}`
},
label: (tooltipItem, data) => {
let dataset = data.datasets[tooltipItem.datasetIndex]
let currentValue = dataset.data[tooltipItem.index]
return `📦 ${currentValue.toLocaleString()}`
}
}
},
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false
}
}
},
mounted () {
this.gradient = this.$refs.canvas
.getContext('2d')
.createLinearGradient(0, 0, 0, 450)
this.gradient.addColorStop(0, 'rgba(52, 217, 221, 0.6)')
this.gradient.addColorStop(0.5, 'rgba(52, 217, 221, 0.25)')
this.gradient.addColorStop(1, 'rgba(52, 217, 221, 0)')
this.renderChart({
labels: this.chartLabels,
datasets: [
{
label: 'downloads',
borderColor: '#249EBF',
pointBackgroundColor: 'rgba(0,0,0,0)',
pointBorderColor: 'rgba(0,0,0,0)',
pointHoverBorderColor: '#249EBF',
pointHoverBackgroundColor: '#fff',
pointHoverRadius: 4,
pointHitRadius: 10,
pointHoverBorderWidth: 1,
borderWidth: 1,
backgroundColor: this.gradient,
data: this.chartData
}
]
}, this.options)
setTimeout(() => {
this.download()
}, 500)
},
methods: {
formatNumber (num) {
let numString = Math.round(num).toString()
let numberFormatMapping = [[6, 'm'], [3, 'k']]
for (let [numberOfDigits, replacement] of numberFormatMapping) {
if (numString.length > numberOfDigits) {
let decimal = ''
if (numString[numString.length - numberOfDigits] !== '0') {
decimal = '.' + numString[numString.length - numberOfDigits]
}
numString = numString.substr(0, numString.length - numberOfDigits) + decimal + replacement
break
}
}
return numString
}
}
}
</script>
You need to notify the child component to re-render itself.
add a watcher is one way, watch the data change and update it.
Another easier way is, add a key prop to it.
in your App.vue, do like this:
<LineChart :chart-data="downloads" :chart-labels="labels" :key="downloads.length"/>
here i'm using the downloads's length as key value. it's a simple and temp resolution to show you how to use key. In your app you should use some other value as key, incase different api call returns same length data.
you can also set the key to another value, and change this value every time you call the api.

Change border of grid

I have following code that I creating a grid
var store = Ext.create('Ext.data.ArrayStore', {
fields: [
{ name: 'company' },
{ name: 'price', type: 'float' },
{ name: 'change', type: 'float' },
{ name: 'pctChange', type: 'float' }
],
data: myData
});
var grid = Ext.create('Ext.grid.Panel', {
store: store,
renderTo: 'divGrid',
columns: [
{ text: 'Company',
flex: 1,
dataIndex: 'company'
},
{ text: 'Price',
flex: 1,
dataIndex: 'price'
},
{ text: 'Change',
flex: 1,
dataIndex: 'change'
},
{ text: '% Change',
flex: 1,
dataIndex: 'pctChange'
}],
height: 250,
width: '100%',
title: 'Array Grid',
renderTo: 'grid-example',
viewConfig: {
stripeRows: true
}
});
});
I want to change color and width of border grid. How can I do it ?
Quick and dirty you can set this config on any grid or really any component that draws a box:
style: 'border: solid Red 2px'
The more correct way is to create a css rule and set cls:'myRedBorderRule' in the config.
EDIT:
var grid = Ext.create('Ext.grid.Panel', {
store: store,
renderTo: 'divGrid',
style: 'border: solid Red 2px',
.....
ExtJS Grid Panel class provides you with parameters to define your custom styles. You can make use of the following class parameters :
border
bodyStyle
bodyCls
bodyBorder
bodyPadding
You can use combination of these parameters to manipulate the grid's border and body styles. Refer to the docs for details of these parameters.
Add below css to remove border
.x-panel-body .x-grid-item-container .x-grid-item {
border: none;
}