use vue.js with chartist.js to create a chart that track balance progress - vue.js

I'm doing some training to better learn how to use vue.js and electron. I've decided to make a simple app to track the profit/loose of a trading day. I will calculate the difference between the end balance and the start balance of every day with a subtraction operation. After some trouble I'm able to get the result of the operation on the DOM using the computed function of vue. What I want to do is to use chartist.js to create a simple chart that will track the results after it is calculated. I'm not sure how to proceed, what I want is to have on the chart every end balance with the calculated difference with the previous amount showed. Can anyone help me with an example?
My actual vue.js code
let app = new Vue({
el: '#app',
data: {
s: '',
e: '',
},
computed: {
tot(){
return Number(this.e) - Number(this.s);
}
}
});
Sample data:
DAY INIT. BALANCE FINAL BALANCE
20/03/2020 2,309.99 2,332.25
23/03/2020 2,332.25 2,343.30
24/03/2020 2,343,30 2,424.62 (+81,32€)
25/03/2020 2,424.62 2,519.56 (+94,94€)
26/03/2020 2,519.56 2,544.46 (+24,90€)
27/03/2020 1,346.00

You just need two convert your data into two arrays, dates for your x-axis and values for your y-axis.
data () {
return {
input: [
['23/03/2020', '2,309.99', '2,332.25'],
['24/03/2020', '2,343,30', '2,424.62'],
['25/03/2020', '2,424.62', '2,519.56']
],
}
},
computed: {
dates () {
return this.input.map(x=>x[0])
},
values () {
return this.input.map(
x => parseFloat(x[2].replace(',','')) -
parseFloat(x[1].replace(',',''))
)
}
}
example with vue-chartjs: https://jsfiddle.net/ellisdod/9vz2qukj/6/

Related

Vuejs Filter add Span

I'm filtering with vuejs, only the output I want is written in the ".00" span in the comma. how can i do it?
html
1.500 ,00
component
<p class="amount">{{ 1500 | toTL }}</p>
filter
Vue.filter('toTL', function (value) {
return new Intl.NumberFormat('tr-TR', { currency: 'TRY', minimumFractionDigits: 2}).format(value);
});
output
1.500,00
I declared you value in the data() function like so :
data () {
return {
number: '1500,00',
newNumber: [],
}
},
What I did to make this work is make a created function like so :
created() {
this.newNumber = this.number.split(',')
},
Then, in the frontend (your p and span) :
<p>{{ newNumber[0] }}<span>,{{newNumber[1]}}</span></p>
What I did is turn a value into an array by using the split() function.
There is probably a way better solution but this is what I came up with in a short amount of time, I hope it helps.

ChartJS Unix Time Values changed

I'm importing data from a Sybase database into ChartJS in VueJs2. I'm using the vue-chart module
I push the timestamps into an array as Unix times using
this.firstIn(new Date(tnaDetails[0].Sunday_FirstIn).getTime())
So:
[Sunday_FirstIn:2010-01-17 08:00:00.0]
Would convert to
1263708000000
Which I then add to the dataset:
datasets: [{
type: 'line',
label: "First In",
backgroundColor: "green",
data: this.firstIn,
fill: false
}
]
However, when the data is plotted on the graph, the values are changed. The above Unit Timestamp becomes
1263700000000
Which obviously returns the wrong time. I'm not doing anything to the ticks in the options.
Below is a result of the numbers being changed. The console has the original data:
Is there a setting that alters the precision/values of numbers in ChartJS that I'm not aware of?
Thanks.
Seth
For anyone who has any similar problem in future, I patched together a few solutions I found.
Firstly, from here Unix Timestamp in JavaScript, I wrote the method:
getTimeString: function(dateString) {
var hours = new Date(dateString).getHours();
var mins = new Date(dateString).getMinutes();
return Math.round((new Date("1970-02-01 " + hours + ":" + mins)).getTime());
}
The important part here is to make sure you have the same day. Not doing this will cause the ChartJS graph to plot the times in different places on the y-axis, even if the hours are the same.
Then from this StackOverFlow question and the related plunker, in the chart options, I have:
{
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
position: 'left',
ticks: {
callback: value => {
let date = moment(value);
if (date.diff(moment('1970-02-01 23:59:59'), 'minutes') === 0) {
return null;
}
return date.format('H:mm');
},
stepSize: 3.6e+6
}
}]
}, //end scales
tooltips: {
callbacks: {
label: function(toolTipItem, data) {
let date = moment(toolTipItem.yLabel);
if (date.diff(moment('1970-02-01 23:59:59'), 'minutes') === 0) {
return null;
}
return date.format('H:mm');
}
}
}
}
Pay attention to the callbacks. They will format the time, calculating the difference from a set time to the time you need plotted. In the first function, you could really use any day, it wouldn't matter, as long as it's the same day. The stepSize will display hourly intervals on the yAxis.

data change doesn't reflect in vue application

In my Vue application I am trying to create a simple table with changeable column sequence. In the data structure I keep all column data with its thead. I use compute to calculate rows from column data using matrix transposion. However any change I do to dynamicTable.columns doesn't reflect in the view.
function transpose(a)
{
return a[0].map(function (_, c) { return a.map(function (r) { return r[c]; }); });
// or in more modern dialect
// return a[0].map((_, c) => a.map(r => r[c]));
}
var tData = {
columns:[
{thead:'isbn',
tdata:[1,2]},
{thead:'name',
tdata:['rose','flower']},
{thead:'price',
tdata:['10','15']},
{thead:'author',
tdata:['john','jane']},
{thead:'page count',
tdata:['396','149']},
{thead:'print date',
tdata:['2001', '1996']}
]
}
var dynamicTable = new Vue({
el: '#dynamicTable',
data: tData,
computed:{
rows: function(){
arr = [];
this.columns.forEach(function(element){
arr.push(element.tdata);
});
return transpose(arr)
}
}
})
For example I want to change the order of isbn column with price,
a=dynamicTable.columns[0]
b=dynamicTable.columns[2]
dynamicTable.columns[0]=b
dynamicTable.columns[1]=a
data changes but changes are not reflected. What is the problem here?
As mentioned in the documentation, this is a JavaScript limitation. Direct changes to an array are not detected by Vue.
One workaround for this, is to use Vue.set(), as instructed in the link.

How to localize the alloyui scheduler component?

I am trying to fully localize the alloyui scheduler in French.
Following this article: How can I get a localized version of a YUI 3 or AlloyUI component? the job is almost done.
However I am still missing tips for two things:
- I need the time format in the left column to be changed from 1-12am/pm to 1-24
- I don't succeed to localize the "All day" term in the left top corner (or at least a way to hide it).
Any help will be welcome
To change to a 24 hour clock, you need to set the isoTime attribute to true for each SchedulerView subclass that you are using.
To internationalize the strings, you need to set the strings attribute of Scheduler, SchedulerDayView SchedulerWeekView, SchedulerMonthView, SchedulerAgendaView, and SchedulerEventRecorder as well as setting YUI's lang attribute to the locale of your choice. For example, I've used Google Translate* to internationalize the Scheduler below for Spanish users:
YUI({lang: 'es-ES'}).use('aui-scheduler', function (Y) {
var es_ES_strings_allDay = { allDay: 'todo el dia' };
new Y.Scheduler({
render: true,
// https://alloyui.com/api/classes/A.Scheduler.html#attr_strings
// https://github.com/liferay/alloy-ui/blob/3.0.3-deprecated.65/src/aui-scheduler/js/aui-scheduler-base.js#L606-L622
strings: {
agenda: 'agenda',
day: 'día',
month: 'mes',
today: 'hoy',
week: 'semana',
year: 'año'
},
views: [
// https://alloyui.com/api/classes/A.SchedulerDayView.html#attr_strings
// https://github.com/liferay/alloy-ui/blob/3.0.3-deprecated.65/src/aui-scheduler/js/aui-scheduler-view-day.js#L363-L373
new Y.SchedulerDayView({
isoTime: true,
strings: es_ES_strings_allDay
}),
// https://alloyui.com/api/classes/A.SchedulerWeekView.html#attr_strings
// SchedulerWeekView extends SchedulerDayView: https://github.com/liferay/alloy-ui/blob/3.0.3-deprecated.65/src/aui-scheduler/js/aui-scheduler-view-week.js#L19
new Y.SchedulerWeekView({
isoTime: true,
strings: es_ES_strings_allDay
}),
// https://alloyui.com/api/classes/A.SchedulerMonthView.html#attr_strings
// https://github.com/liferay/alloy-ui/blob/3.0.3-deprecated.65/src/aui-scheduler/js/aui-scheduler-view-week.js#L19
new Y.SchedulerMonthView({
isoTime: true,
strings: {
showMore: 'mostrar {0} más',
close: 'cerrar'
}
}),
// https://alloyui.com/api/classes/A.SchedulerAgendaView.html#attr_strings
// https://github.com/liferay/alloy-ui/blob/3.0.3-deprecated.65/src/aui-scheduler/js/aui-scheduler-view-week.js#L19
new Y.SchedulerAgendaView({
isoTime: true,
strings: {
noEvents: 'No hay eventos futuros'
}
})
],
// https://alloyui.com/api/classes/A.SchedulerEventRecorder.html#attr_strings
// https://github.com/liferay/alloy-ui/blob/3.0.3-deprecated.65/src/aui-scheduler/js/aui-scheduler-view-week.js#L19
eventRecorder: new Y.SchedulerEventRecorder({
strings: {
'delete': 'borrar',
'description-hint': 'descripción insinuación',
cancel: 'cancelar',
description: 'descripción',
edit: 'editar',
save: 'salvar',
when: 'cuando'
}
})
});
});
* I don't recommend using Google Translate to internationalize a production application since there are many nuances to internationalization that a machine translation will miss.

Filter other columns based on first columns

I'm using jquery data tables and I'm assigning an array of values to the initialization of the data table. The table basically looks like this.
based on an an radio button I would like to limit the items that are display in the table and the items that are searched in the table.
For my example it would be based on the "Chart column". I want to limit the table to only show the items that are based on chart "D" or Chart "S". Here is how I'm initializing the table.
if (!$.fn.DataTable.isDataTable( '#fundLookUptbl' ) ) {
fundTable = $('#fundLookUptbl').DataTable( {
data: funds,
columns: [
{ "mData": "chart" },
{ "mData": "fund" },
{ "mData": "orgDefault" },
{ "mData": "progDefault" }
]
} );
var filteredData = fundTable
.columns( [0, 1] )
.data()
.eq( 0 )
.filter( function ( value, index ) {
return value = 'D' ? true : false;
} );
}
This is obviously not working, and the filterData variable is a lousy attempt on trying to make it work. I'm having a hard time understanding the API's. So the question is , How can initialize the table to only show the items that are based on a given chart. I know that I can remove the items of the array but i don't want to do that since I would simple like to be able to switch between chart "D" and "S" but still continue to search through the other columns.
I believe that filtering the column would solve your problem.
table.column(0).search('Bruno').draw()
So you could just filter the column when the radio button selection change
Here is a fiddle example
I´m not sure to be understanding what you want to do but here are some options:
One way is selecting by default value example "s". You can use a dropdown is easier to handled .Then select with jQuery the dafault value "s" on that dropdown and add a function
$("#DropdownId").change(function () {
var chart=$("#DropdownId").val();
});
$.ajax({
url: "url")",//url to reload page with new value
type: "POST",
data: {chart:chart},
success: function (data) {
}
});
});
on this way the filter is on backend. If you want to do something on the row depending of a column value you shoud to add something like this
"fnRowCallback": function (nRow, mData, iDisplayIndex, iDisplayIndexFull) {
if (mData["chart"] =="s") {
return nRow;
}
},
Datatables: custom function inside of fnRowCallback.
Good luck
fundTable.order( [0, 'asc'] );
Try that or look at this particular page for reference:
https://datatables.net/reference/api/order%28%29
Basically orders in pair of columnIndex in either asc(ending) or desc(ending) order.