How to make a sum of value in data with Vue.js and use it in of v-if? - vue.js

I want to make a function to sum up the value in data with vue.js but I don't know how to code it.
var quiz = {
questions: [
{
text: "who am I?",
responses: [
{ text: "John", value: 1000 },
{ text: "James", value: 2000 },
{ text: "Lucy", value: 3000 },
{ text: "Mari", value: 4000 }
]
},
{
text: "What do you want to be?",
responses: [
{ text: "first selector", value: 10 },
{ text: "second selector", value: 20 },
{ text: "third selector", value: 30 },
{ text: "fourth selector", value: 40 }
]
},
{
text: "How old are you?",
responses: [
{ text: "first selector", value: 10 },
{ text: "second selector", value: 20 },
{ text: "third selector", value: 30 },
{ text: "fourth selector", value: 40 }
]
}
]
}
and html code
<template v-if="resultOne">
<p>First result</p>
</template>
I had a following data like this, and I want to make some v-if code by using the value of them.
For example, if the sum of value become 1020, 1030, 1040, and 1050, I want to show "resultOne."
How can I make a code like this?

It's difficult to give you a complete answer as I don't know where quiz is coming from. Is it hardcoded or is it dynamic?
But either way, here is a method you can use to calculate the total value of the data:
const totalValue = quiz.reduce((total, item) => {
const itemSum = item.responses.reduce((sum, response) => {
return sum + response.value;
}, 0);
return total + itemSum;
}, 0);
If the data is static then I would suggest just doing the calculation inside a created() hook and storing it in a data prop.
like:
data() {
return {
totalValue: 0
}
},
created() {
this.calculateValue();
},
methods: {
calculateValue() {
this.totalValue = quiz.reduce((total, item) => {
const itemSum = item.responses.reduce((sum, response) => {
return sum + response.value;
}, 0);
return total + itemSum;
}, 0);
}
}
and then your v-if is simply v-if="[1020, 1030, 1040, 1050].includes(totalValue)"
If quiz is more dynamic then you can try to use a computed method.

Related

how to pass i18n data $t as prop to a component

in a normal way with out translation but i want to translate the two object array and bind into a component
<InfoNews
v-for="infonew in infonews"
:id="infonew.id"
:title="infonew.title"
:content="infonew.content"
/>
data() {
return {
infonews: [
{
id: "01",
title: "what we do",
content:"industke aecimen book. ",
},
{
id: "02",
title: "our mission",
content:"ggdddg",
},
],
};
Make infonews a computed property. The title and content of each should be the translation keys.
export default {
computed: {
infonews() {
return [
{
id: "01",
title: this.$t("what we do"),
content: this.$t("industke aecimen book"),
},
{
id: "02",
title: this.$t("our mission"),
content: this.$t("ggdddg"),
},
]
};
}
}

How to combine Filtering, Grouping, and Sorting in Kendo UI Vue Grid (native)

I'm trying to enable some operations on my grid such as grouping, filtering and sorting, individually they works as shown in the docs but there is no an example of those functionality working together.
By myself I was able to combine sorting and filtering but grouping does not work when i'm adding it as it shown in the docs. look at at my code
<template>
<div>
<Grid :style="{height: '100%'}"
ref="grid"
:data-items="getData"
:resizable="true"
:reorderable="true"
#columnreorder="columnReorder"
:filterable="true"
:filter="filter"
#filterchange="filterChange"
:sortable="true"
:sort= "sort"
#sortchange="sortChangeHandler"
:groupable="true"
:group= "group"
#dataStateChange="dataStateChange"
:columns="columns">
</Grid>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
editID: null,
columns: [
{ field: 'AbsenceEmployeID', filterable:false, editable: false, title: '#'},
{ field: 'Employe', title: 'Employer', cell: DropDownEmployes},
{ field: 'Remarque', title: 'Remarque'},
{ field: 'Type', title: 'Type', cell: DropDownTypes},
{ field: 'CreatedDate', filter:'date', editable: false, editor: 'date', title: 'créé le', format: '{0:d}'},
{ title: 'Actions', filterable:false, cell: CommandCell}
],
filter: {
logic: "and",
filters: []
},
sort: [
{ field: 'CreatedDate', dir: 'desc' }
],
group: [],
gridData: []
}
}
mounted() {
this.loadItems()
},
computed: {
absencesList() {
return this.items.map((item) => Object.assign({ inEdit: item.AbsenceEmployeID === this.editID}, item));
},
getData() {
return orderBy(filterBy(this.absencesList, this.filter), this.sort);
},
...mapState({
absences: state => state.absences.absences
})
}
methods: {
loadItems () {
this.$store.dispatch('absences/getAbsences')
.then(resp => {
this.items = this.absences.map(item => item)
})
},
filterChange: function(ev) {
this.filter = ev.filter;
},
columnReorder: function(options) {
this.columns = options.columns;
},
sortChangeHandler: function(e) {
this.sort = e.sort;
},
// the following is for grouping but not yet used, read more
groupedData: function () {
this.gridData = process(this.getData, {group: this.group});
},
createAppState: function(dataState) {
this.group = dataState.group;
this.groupedData();
},
dataStateChange: function (event) {
this.createAppState(event.data);
},
}
}
</script>
The last three methods are not used yet, so filtering and sorting is working perfectly as of now. then in other to enable grouping I want to replace :data-items="getData" by :data-items="gridData" and run this.groupedData() method after the items are loaded but grouping doesn't work.
I think everything should be handle by the dataStateChange event and process() function but I also tried but without success
If you define the filterchange and sortchange events they are being triggered for filter and sort and you will have to updated data in their handlers. If you rather want to use datastatechage event for all the changes you have to remove the filterchange and sortchange events and the datastatechage event will be triggered instead of them. In this case you will have to update the data in its handler.
You can use the process method of #progress/kendo-data-query by passing the respective parameter each data change that is needed as in the example below:
const result = process(data, {
skip: 10,
take: 20,
group: [{
field: 'category.categoryName',
aggregates: [
{ aggregate: "sum", field: "unitPrice" },
{ aggregate: "sum", field: "unitsInStock" }
]
}],
sort: [{ field: 'productName', dir: 'desc' }],
filter: {
logic: "or",
filters: [
{ field: "discontinued", operator: "eq", value: true },
{ field: "unitPrice", operator: "lt", value: 22 }
]
}
});
Hers is a sample stackblitz example where such example is working correctly - https://stackblitz.com/edit/3ssy1k?file=index.html
You need to implement the groupchange method to handle Grouping
I prefer to use process from #progress/kendo-data-query
The following is a complete example of this
<template>
<Grid :style="{height: height}"
:data-items="gridData"
:skip="skip"
:take="take"
:total="total"
:pageable="pageable"
:page-size="pageSize"
:filterable="true"
:filter="filter"
:groupable="true"
:group="group"
:sortable="true"
:sort="sort"
:columns="columns"
#sortchange="sortChangeHandler"
#pagechange="pageChangeHandler"
#filterchange="filterChangeHandler"
#groupchange="groupChangeHandler"
/>
</template>
<script>
import '#progress/kendo-theme-default/dist/all.css';
import { Grid } from '#progress/kendo-vue-grid';
import { process } from '#progress/kendo-data-query';
const sampleProducts = [
{
'ProductID': 1,
'ProductName': 'Chai',
'UnitPrice': 18,
'Discontinued': false,
},
{
'ProductID': 2,
'ProductName': 'Chang',
'UnitPrice': 19,
'Discontinued': false,
},
{
'ProductID': 3,
'ProductName': 'Aniseed Syrup',
'UnitPrice': 10,
'Discontinued': false,
},
{
'ProductID': 4,
'ProductName': "Chef Anton's Cajun Seasoning",
'UnitPrice': 22,
'Discontinued': false,
},
];
export default {
components: {
Grid,
},
data () {
return {
gridData: sampleProducts,
filter: {
logic: 'and',
filters: [],
},
skip: 0,
take: 10,
pageSize: 5,
pageable: {
buttonCount: 5,
info: true,
type: 'numeric',
pageSizes: true,
previousNext: true,
},
sort: [],
group: [],
columns: [
{ field: 'ProductID', filterable: false, title: 'Product ID', width: '130px' },
{ field: 'ProductName', title: 'Product Name' },
{ field: 'UnitPrice', filter: 'numeric', title: 'Unit Price' },
{ field: 'Discontinued', filter: 'boolean', title: 'Discontinued' },
],
};
},
computed: {
total () {
return this.gridData ? this.gridData.length : 0;
},
},
mounted () {
this.getData();
},
methods: {
getData: function () {
this.gridData = process(sampleProducts,
{
skip: this.skip,
take: this.take,
group: this.group,
sort: this.sort,
filter: this.filter,
});
},
// ------------------Sorting------------------
sortChangeHandler: function (event) {
this.sort = event.sort;
this.getData();
},
// ------------------Paging------------------
pageChangeHandler: function (event) {
this.skip = event.page.skip;
this.take = event.page.take;
this.getData();
},
// ------------------Filter------------------
filterChangeHandler: function (event) {
this.filter = event.filter;
this.getData();
},
// ------------------Grouping------------------
groupChangeHandler: function (event) {
this.group = event.group;
this.getData();
},
},
};
</script>

pass an array of api keys to a const in react native

This api returns an array of 20 items, I would like to use/pass two keys to a function.
[
{ 0
close: 172.26
label: "Jan 2"
},
{
close: 172.23
label: "Jan 3"
...
My goal is to generate a graph chart, the library require some data in that format:
const data = [
[{
"x": 0,
"y": 123
}, {
"x": 1,
"y": 456
}, {
"x": 2,
"y": 789
}],
];
I have to dynamically generate those x and y by replacing them with api results, how can I achieve that?
Solution to your problem:
const data = [
[{
close: 172.26,
label: "Jan 2"
}, {
close: 172.23,
label: "Jan 3"
}]
];
data[0] = data[0].map(item => {
const { close: y, label: x } = { ...item }
return { x, y }
});
console.log(data)
and in react-native you can do the following:-
constructor() {
super();
this.state = {
data: [
[{
close: 172.26,
label: "Jan 2"
},
{
close: 172.23,
label: "Jan 3"
}]
]
}
}
componentWillMount() {
let { data } = this.state;
data[0] = data[0].map(item => {
const { close: y, label: x } = { ...item }
return { x, y }
});
this.setState({ data });
}
I hope it will help you.

formatting cell values in datatables

Using this as an example how do I control the format of the values in the cells?
for example, how would I format the Extn. column to read 5,407 or 54.07?
Name Position Office Extn. Start date Salary
Airi Satou Accountant Tokyo 5407 $2008/11/28 $162,700
I have been searching here and here but I can't quite work it out. can anyone advise?
I have tried something like this, but am having no success:
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
{ title: "Extn." },
{ title: "Start date" },
{ title: "Salary" }
],
"aoColumnDefs": [ {
"aTargets": [ 4 ],
"mRender": function (data, type, full) {
//var formmatedvalue=data.replace("TEST")
//return formmatedvalue;
return '$'+ data;
}
}]
} );
} );
Use the columns.render option.
Either with the built-in helper, to get a thousand seperator (5,407):
{
title: "Extn.",
render: $.fn.dataTable.render.number(',', '.', 0, '')
},
JSFiddle example
Or do it yourself with a custom function (54.07):
{
title: "Extn.", render: function (data, type, row) {
return data / 100;
}
},
JSFiddle example

Need to use Remote Kendo Grouped and Stacked Bar Chart

I am using Kendo Bar Chart, which will show like grouped and stacked for dynamic data. In category field i need to display usernames and it has to show respective metric values, here metric values are dynamic and variable, and metric count values are displayed in bar, which is like stacked bar.
For Example:
Metric values are - High, Low, Medium, ...
Metric values count -> High-4, Low-2, and medium -5 ,..
Here counts 4,2, and 5 to be shown in a stacked bar.
Like this i have to show for multiple users with respective the values.
Below i have shown my Code, may i know how to use dynamic stacked bar kendo chart, and can i have solution for above mentioned problem.
Code- Chart Definition
$("#chartForWorkItems").kendoChart({
title: {
text: "Bugs State Analysis"
},
//defining the datasource for loading the chart
dataSource: {
transport: {
read: {
url: baseUri + "ProjectReportWorkItemChart/chartDisplayForWorkITems",
cache: false,
type: "POST",
dataType: "json",
complete: function (e) {
},
},
parameterMap: function (options, operation) {
console.log(selectedCategoryByMetrics);
if (operation == "read") {
return {
workItems: selectedCategoryByMetrics,
Projectid: sessionStorage.getItem("prjprojectid"),
metricsWithWorkItem: metricsWithWorkItem,
users: usersSelected
}
}
},
},
schema: {
model: {
id: "field",
fields: {
field: { type: "string" },
count_f: { type: "string" },
metric: { type: "string" },
assignedTo: { type: "string" },
}
}
}
},
chartArea: {
width: 400,
height: 300,
},
seriesDefaults: {
type: "column",
},
series: [{
field: "count_f",
},
],
categoryAxis: {
categories: "assignedTo",
field: "field",
majorGridLines: {
visible: true
}
},
valueAxis: [{ //display count in the value axis
line: {
visible: true
},
majorGridLines: {
visible: true
}
}],
tooltip: { //To display tool tip
visible: true
},
});