this is my first time posting here, i'm working on an application where i need to get data from an API and show it through a chart (i'm using vue chart js). The code is almost done, i can see in the console the API's data.
Showing API's data in console
This is my chart/api conection:
<template>
<div>
<bar-chart
:data="barChartData"
:options="barChartOptions"
:height="150"
:width="150"
/>
</div>
</template>
<script>
import BarChart from "~/components/BarChart";
const chartColors = {
grey: "rgba(210, 210, 210, 0.2)",
white: "rgb(255,255,255)",
};
export default {
components: {
BarChart,
},
data() {
return {
barChartData: {
asistencia: [],
labels: [],
datasets: [
{
label: "Income",
backgroundColor: [chartColors.white, chartColors.grey],
data: [0,0],
},
],
},
barChartOptions: {
responsive: true,
legend: {
display: true,
},
},
};
},
async fetch() {
this.asistencia = await fetch(
'http://127.0.0.1:8000/apiasistenciausuarioAsistenciaUsuario/',
).then(res => res.json())
console.log(this.asistencia);
},
components: {
BarChart,
},
methods: {
refresh() {
this.datos();
this.$nuxt.refresh();
},
datos() {
this.barChartData.datasets[0].data = [
this.res.is_presente,
];
},
}
};
As you can see i send the data to the console but the "Asistencia" graphic is not showing and that's because it isn't getting the data sucessfully
datos() {
this.barChartData.datasets[0].data = [
this.res.is_presente,
];
barChartData should get the data from "is_presente" var from the API but that var is a boolean so i was thinking on doing a validation to check when it's true/false and make a counter to fill the graphic.
datos() {
this.barChartData.datasets[0].data = [
if(this.res.is_presente == true){
count++;
}else{
count--;
}
];
I don't know how to do this, i have the idea but i don't know how to execute this....
Thanks in advance!
Related
I'm implementing a doughnut chart with CanvasJs in a ReactJs App.
Collected following code from CanvasJs's github repo
var React = require("react");
var CanvasJS = require("./canvasjs.min");
CanvasJS = CanvasJS.Chart ? CanvasJS : window.CanvasJS;
class CanvasJSChart extends React.Component {
static _cjsContainerId = 0;
constructor(props) {
super(props);
this.options = props.options ? props.options : {};
this.containerProps = props.containerProps
? props.containerProps
: { width: "100%", position: "relative" };
this.containerProps.height =
props.containerProps && props.containerProps.height
? props.containerProps.height
: this.options.height
? this.options.height + "px"
: "400px";
this.chartContainerId =
"canvasjs-react-chart-container-" + CanvasJSChart._cjsContainerId++;
}
async componentDidMount() {
//Create Chart and Render
this.chart = await new CanvasJS.Chart(this.chartContainerId, this.options);
this.chart.render();
console.log("CHart", this.chart);
if (this.props.onRef) this.props.onRef(this.chart);
}
shouldComponentUpdate(prevProps) {
// //Check if Chart-options has changed and determine if component has to be updated
// return !(nextProps.options === this.options);
if (prevProps.options !== this.props.options) {
return false;
}
else {
return true;
}
}
componentWillUnmount() {
//Destroy chart and remove reference
this.chart.destroy();
if (this.props.onRef) this.props.onRef(undefined);
}
render() {
return <div id={this.chartContainerId} style={this.containerProps} />;
}
}
var CanvasJSReact = {
CanvasJSChart: CanvasJSChart,
CanvasJS: CanvasJS,
};
export default CanvasJSReact;
I'm passing options to the component in the following manner
const options = {
animationEnabled: true,
subtitles: [
{
text: "",
verticalAlign: "center",
fontSize: 24,
dockInsidePlotArea: true,
},
],
data: [
{
type: "doughnut",
indexLabel: "{name}: {percentage}",
yValueFormatString: "'$'#,###",
dataPoints: [{ name: "Unsatisfied", y: 5 },
{ name: "Very Unsatisfied", y: 31 },
{ name: "Very Satisfied", y: 40 },
{ name: "Satisfied", y: 17 },
{ name: "Neutral", y: 7 }],
},
],
};
USE THIS UPPER COMPONENT
<CanvasJSChart options={options} />
When I'm passing dataPoints (with static data) in my code, the chart loads fine.
But the issue occurs when I try to use dynamic data. My dynamic data has only one dataPoint this point of time
// Array of data points
[{
name: "FNBO Evergreen® Rewards Visa® Card",
percentage:"100%",
y: 20000
}]
On Page reload the chart is not rendering. But, it appears back if routed from another page or window size is changed.
The issue can be easily seen the following loom video
https://www.loom.com/share/754b51dae7b04cb29a87a969a961fefc
Note: In all the cases shown in video, we do receive data from backend. But this issue occurs in some of the cases
I want to use #vueup/vue-quill ^1.0.0-beta.7 on my control panel admin based on vue ^3.2.29.
Unfortunately, I noticed that loading HTML content is not working for me. Quill converts <div> tags to <p> tags for me, also removing classy and css styles, which destroys the appearance of the content. On backand i use Laravel.
Can anyone help me with this? I sit on it all day to no avail.
<template>
// [...]
<QuillEditor
ref="mainContent"
v-model:content="form.content"
style="min-height: 300px"
:options="editorOptions"
theme="snow"
content-type="html"
output="html"
#text-change="countMainContent"
/>
// [...]
</template>
<script>
import { QuillEditor, Quill } from "#vueup/vue-quill";
import "#vueup/vue-quill/dist/vue-quill.snow.css";
import BlotFormatter from "quill-blot-formatter";
import QuillImageDropAndPaste, { ImageData } from "quill-image-drop-and-paste";
import ArticleCategoryField from "../forms/ArticleCategoryField.vue";
import htmlEditButton from "quill-html-edit-button";
import useVuelidate from "#vuelidate/core";
import { required } from "../../utils/i18n-validators";
Quill.register({
"modules/blotFormatter": BlotFormatter,
"modules/htmlEditButton": htmlEditButton,
"modules/imageDropAndPaste": QuillImageDropAndPaste,
});
// [...]
data() {
return {
// [...]
editorOptions: {
handlers: {
// handlers object will be merged with default handlers object
link: function (value) {
if (value) {
var href = prompt("Enter the URL");
this.quill.format("link", href);
} else {
this.quill.format("link", false);
}
},
},
modules: {
toolbar: [
["bold", "italic", "underline", "strike"], // toggled buttons
["blockquote", "code-block"],
[{ header: 1 }, { header: 2 }], // custom button values
[{ list: "ordered" }, { list: "bullet" }],
[{ script: "sub" }, { script: "super" }], // superscript/subscript
[{ indent: "-1" }, { indent: "+1" }], // outdent/indent
[{ direction: "rtl" }], // text direction
[{ size: ["small", false, "large", "huge"] }], // custom dropdown
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }], // dropdown with defaults from theme
[{ font: [] }],
[{ align: [] }],
["image", "link", "video"],
["clean"], // remove formatting button
],
blotFormatter: {},
htmlEditButton: {
debug: false,
msg: "Edytuj zawartość przy pomocy HTML",
cancelText: "Anuluj",
buttonTitle: "Pokaż kod źródłowy HTML",
},
imageDropAndPaste: {
handler: this.imageHandler,
},
},
},
// [...]
}
}
// [...]
methods: {
getArticle() {
if (this.articleId) {
this.$axios
.get("article/" + this.articleId, {
headers: {
Accept: "application/json",
Authorization: `Bearer ${this.$store.state.auth.token}`,
},
})
.then((response) => {
this.form.title = response.data.article.title;
this.form.mainImage =
response.data.article.uploaded_file_id;
this.form.category =
response.data.article.categories[0].id ?? 0;
this.$refs.mainContent.pasteHTML(
response.data.article.content
);
this.form.articleGallery = this.prepareGallery(
response.data.article.images
);
})
.catch((error) => {
if (process.env.MIX_APP_DEBUG)
this.$toast.error(error.message);
throw new Error(error);
});
}
},
// [...]
I know its bit late. But posting this to help those who visit this question.
I had the same problem. When i tried to load contents into use #vueup/vue-quill editor on the edit page, there were complications. I could load delta, html and plain text using setContents(),setHTML() etc, but after that the problem was that when i tried to type inside the same editor js errors occur. The only solution i found was to implement the quill on own. Sharing my experience to help others.
//do bootstrap if needed
// import './bootstrap';
import { createApp } from 'vue';
import { watch, ref, nextTick } from 'vue'
import axios from 'axios';
import Quill from "quill";
import "quill/dist/quill.core.css";
import "quill/dist/quill.bubble.css";
import "quill/dist/quill.snow.css";
createApp({
data() {
return {
mainContentEditor: null,
mainContentEditorValue: '',
}
},
mounted() {
this.initMainContentEditor();
//call this to get article on load
this.getArticle();
},
methods: {
//initiate the main content editor
initMainContentEditor() {
var _this = this;
this.mainContentEditor = new Quill(this.$refs.mainContentEditor, {
modules: {
toolbar: [
[
{
header: [1, 2, 3, 4, false],
},
],
["bold", "italic", "underline", "link"],
],
},
//theme: 'bubble',
theme: "snow",
formats: ["bold", "underline", "header", "italic", "link"],
placeholder: "Type something in here!",
});
//register the event handler
this.mainContentEditor.on("text-change", function () {
_this.mainContentEditorChanged();
});
},
//this method is called when the editor changes its value
mainContentEditorChanged() {
console.log("main content changed!");
// do somethign with it like assign it to mainContentEditorValue
this.mainContentEditorValue = this.mainContentEditor.root.innerHTML;
},
getArticle() {
//do the api call to get the article response.
//once you get the respose
// assign the html content to quill editor
// check getArticle() method on question to fill this part
//replace
// this.$refs.mainContent.pasteHTML(
// response.data.article.content
// );
// with this
this.mainContentEditor.root.innerHTML = response.data.article.content;
}
}
}).mount('#app')
html/template
<div id="app">
<div ref="mainContentEditor"></div>
</div>
You can make it to a component and reuse it. I shared it to just show a working implementation.
I'm a beginner in Vue and I'm using vue-apex chart to create a chart in my application. I want to display in chart, the values of the two component's properties "uncorrectAns" and "correctAns" that I compute thanks to a specific method (computeStat()).
<template>
<apexcharts width="500" type="bar" :options="chartOptions" :series="series"></apexcharts>
</template>
<script>
export default {
name: 'Results',
components: {
apexcharts: VueApexCharts
},
data() {
return {
results: '',
correctAns: 0,
uncorrectAns: 0,
chartOptions: {
chart: {
id: 'vuechart-example'
},
xaxis: {
categories: ['Correct Answers', 'Uncorrect Answers']
}
},
series: [
{
name: 'series-1',
data: [this.correctAns, this.uncorrectAns]
}
]
}
},
methods: {
computeStat() {
var i
for (i = 0; i < this.results.length; i = i + 1) {
if (this.results[i].answerCorrect == true) {
this.correctAns = this.correctAns + 1
} else {
this.uncorrectAns = this.uncorrectAns + 1
}
}
}
},
created() {
this.results = this.$route.params.output
this.computeStat()
var i
for (i = 0; i < this.results.length; i = i + 1) {
console.log('bestPractice ' + i + ':' + this.results[i].bestPract)
}
}
}
</script>
When I run the application, the chart isn't displayed and I get this error message on the browser console:
I would like to know the nature of this error and if there is a correct way to display "correctAns" and "uncorrectAns" values in the chart.
There's a couple of problems here around your series property...
When you define series, both this.correctAns and this.uncorrectAns are undefined (this is the source of your problem)
Because series is statically defined, it will never update as you make changes to this.correctAns and this.uncorrectAns
The solution is to convert series into a computed property. Remove it from data and add
computed: {
series () {
return [
{
name: 'series-1',
data: [this.correctAns, this.uncorrectAns]
}
]
}
}
Demo ~ https://jsfiddle.net/ynLfabdz/
Given you seem to be treating results as an array, you should initialise it as such instead of an empty string, ie
results: [], // not ''
I fixed the issue by simple check if the array is undefined then return empty if not return the chart with my values
const Amount = [
{
name: 'Salary Amount',
data: salary[0] === undefined ? [] : salary
},
{
name: 'Over Time Amount',
data: overTime[0] === undefined ? [] : overTime
},
true
]
I have been struggling with this one for days now, really need some help. I need to apply gradient colors and some custom styling to our ChartJs bar chart, that contains call reporting data which comes from the back-end server. I found a way how to apply the styles and gradients, but can't figure out how to configure datasets to display correct data from the server, instead of some random numbers (eg. 10,20,30), like I tried for gradientGreen below. Any ideas?
//main html
<div class="row mb-4 mt-4">
<div class="col-9">
<h4 class="text-center">Call Distribution</h4>
#await Component.InvokeAsync("HourlyCallTotals", new { from = Model.From, to = Model.To, customer = Model.customer, site = Model.site })
</div>
//component html
#model CallReporter.ViewModels.BasicFilter
<div id="hourlyChart">
</div>
<script>
var HourlyCallData = #Html.RenderAction("HourlyTotals", "Calls", "", new { from = Model.from.ToString("s"), to = Model.to.ToString("s"), customer = Model.customer, site = Model.site })
</script>
//relevant part of JS function for Chart
function hoursChartAjax() {
var hourlyChart = $('#hourlyChart').html('<canvas width="400" height="300"></canvas>').find('canvas')[0].getContext('2d');
// set gradients for bars
let gradientGreen = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientGreen.addColorStop(0, '#66d8b0');
gradientGreen.addColorStop(1, '#1299ce');
let gradientBlue = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientBlue.addColorStop(0, '#1299ce');
gradientBlue.addColorStop(1, '#2544b7');
if (hourlyChart !== undefined) {
$.get(base + "Calls/HourlyTotals", { from: from.format(), to: to.format(), customer: currentCustomer.id, site: currentSite }, function (data) {
// set the default fonts for the chart
Chart.defaults.global.defaultFontFamily = 'Nunito';
Chart.defaults.global.defaultFontColor = '#787878';
Chart.defaults.global.defaultFontSize = 12;
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: ['6AM', '9AM', '12AM', '3PM', '6PM', '9PM', '12PM'],
datasets: [
{
label: 'Total outgoing calls',
backgroundColor: gradientBlue,
data: HourlyCallData
},
{
label: 'Total incoming calls',
backgroundColor: gradientGreen,
data: [10, 20, 30]
}
]
},
//relevant part of back-end code that returns call data as Json
totalsContainer.Totals = allCallsHourly.OrderBy(x => x.Date).ToList();
return Json(new
{
labels = totalsContainer.Totals.Select(x => x.Date.ToString("hh tt")),
datasets = new List<object>() {
new { label = "Total Outgoing Calls", backgroundColor = "#1299CE", data = totalsContainer.Totals.Select(x => x.TotalOutgoingCalls) },
new { label = "Total Incoming Calls", backgroundColor = "#00B050", data = totalsContainer.Totals.Select(x => x.TotalIncomingCalls) } }
});
Attached img with console log and error, after trying solution below:
If the data comes formatted in the right way, you can just write this:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: data: data
}
If not you could do it like so:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: data.labels,
datasets: [
{
label: data.datasets[0].label,
backgroundColor: gradientBlue,
data: data.datasets[0].data
},
{
label: data.datasets[1].label,
backgroundColor: gradientGreen,
data: data.datasets[1].data
}
]
}
}
I´m developing a visualization module for some crypto portfolios with vue.js and chart.js but am currently stuck with this:
Empty chart is displayed but non of the values are rendered.
Since the values are dynamically loaded after the chart is initialized I believe that the chart is not updating itself properly (even though I call .update()), but no errors are displayed whatsoever.
I wrapped the chart.js rendering in a vue component:
Vue.component('portfolioValues', {
template: '<canvas width="400" height="200"></canvas>',
data: function() {
return {
portfolio_value: [],
portfolio_labels: [],
chart: null,
}
},
methods: {
load_portfolio_value_local: function() {
values = [];
labels = []
local_data.forEach(element => {
values.push(element.total_usd);
labels.push(moment(element.timestamp, 'X'));
});
this.portfolio_value = values;
this.portfolio_labels = labels;
this.chart.update();
},
render_chart: function() {
this.chart = new Chart(this.$el, {
type: 'line',
data: {
labels: this.portfolio_labels,
datasets: [{
label: "Portfolio Value",
data: this.portfolio_value,
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
}]
}
}
});
}
},
mounted: function() {
this.render_chart();
this.load_portfolio_value_local();
}
});
For demonstration purposes I just added some data locally, looks like this:
local_data = [{
"timestamp": 1515102737,
"total_btc": 0.102627448096786,
"total_usd": 1539.41274772627
}, {
"timestamp": 1515102871,
"total_btc": 0.102636926127186,
"total_usd": 1538.52649627725
}, {
"timestamp": 1515103588,
"total_btc": 0.102627448096786,
"total_usd": 1532.33042753311
}
]
Here is the full demo code: https://codepen.io/perelin/pen/mppbxV
Any ideas why no data gets rendered? thx!
The problem you have here is how vuejs handles its data.
If you use it like that:
local_data.forEach(element => {
this.portfolio_value.push(element.total_usd);
this.portfolio_labels.push(moment(element.timestamp, 'X'));
});
this.chart.update();
The chart will update. But by re-initializing the arrays you work against vuejs.
TL;DR
If you want to re-initialize an object, you could assign the array to the object:
Object.assign(this.portfolio_value, values);
Object.assign(this.portfolio_labels, labels);
That way, the linking stays working.