Creating a Buefy table from a VueJs table - vue.js

I've been trying to create a table with Buefy from a VueJs table.
My VueJs table gets data from a JSON file.
Here is my JSON file :
{
"1":
{
"Date":"01/01/2016",
"New":0,
"In progress":0,
"Sent":0,
"Fail":0
},
"2":
{
"Date":"01/01/2015",
"New":0,
"In progress":0,
"Sent":0,
"Fail":3
}
}
My VueJs code :
<template>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>Date</th>
<th>New</th>
<th>In prrogress</th>
<th>Sent</th>
<th>Dail</th>
</tr>
</thead>
<tr v-for="sms in sms">
<td v-for="sms in sms">{{sms}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data () {
return {
sms: ''
}
},
created () {
this.$http.post('api.php',{object : 'data', action : 'fetch'})
.then(
response => {
this.sms = response.body
})
.catch(function(error){
console.log(error)
})
}
}
</script>
The result is :
I want to get the same result using Buefy table so i did :
<template>
<b-table :data=data :columns="columns"></b-table>
</template>
<script>
export default {
data() {
return {
data: [
],
columns: [
{
field: "Date",
label: 'Date',
centered: true
centered: true
},
{
field: "New",
label: "New",
centered: true
centered: true
},
{
field: "In progress",
label: "In progress",
centered: true
centered: true
},
{
field: "Sent",
label: "Sent",
centered: true
},
{
field: "Fail",
label: "Fail",
centered: true
centered: true
}
]
}
},
methods: {
loadData(){
this.$http.post('api.php',{object : 'data', action : 'fetch'}).then(({ data }) => {
this.data = data.body
})
}
},
mounted() {
this.loadData()
}
}
</script>
but I'm getting this empty table :

Related

Vuejs get dynamic form values

I have select and input component with made by buefy. Everything is ok till I realize how can I get the data.
I'm sort of new on vuejs. So I will be glad if you help me out.
I'm getting dynamic form from backend
So my question is how can get values these inputs and submit to backend again with getOffer() methot.
Here is my codes;
Input.vue
<template>
<b-field :label="fieldLabel">
<b-input
:name="inputName"
:type="inputType"
:maxlength="inputType == 'textarea' ? 200 : null"
></b-input>
</b-field>
</template>
<script>
export default {
name: "Input",
props: {
inputType: {
type: String,
required: true,
default: "text",
},
inputName: {
type: String,
required: true,
},
fieldLabel: {
type: String,
required: true,
}
}
};
</script>
Home.vue
<template>
<div class="container is-max-desktop wrapper">
<div v-for="element in offer" :key="element.id">
<Input
v-model="element.fieldValue"
:value="element.fieldValue"
:fieldLabel="element.fieldLabel"
:inputType="element.fieldType"
:inputName="element.fieldName"
v-if="element.fieldType != 'select'"
class="mb-3"
/>
<Select
v-model="element.fieldValue"
:fieldLabel="element.fieldLabel"
:options="element.infoRequestFormOptions"
:selectName="element.fieldName"
v-if="element.fieldType == 'select'"
class="mb-3"
/>
</div>
<b-button type="is-danger" #click="getOffer()">GET</b-button>
</div>
</template>
<script>
import axios from "axios";
import Select from "../components/Select.vue";
import Input from "../components/Input.vue";
export default {
name: "Home",
data() {
return {
offer: [],
};
},
components: {
Select,
Input,
},
methods: {
getOfferForm() {
axios({
method: "get",
url: `/GETDYNAMICFORM`,
})
.then((response) => {
this.offer = response.data;
})
.catch(() => {
this.$buefy.toast.open({
duration: 3000,
message: "oops",
position: "is-bottom",
type: "is-danger",
});
});
},
getOffer() {
console.log(this.offer);
},
},
created() {
this.getOfferForm();
},
};
</script>
Example Dynamic Form Response like;
[
{
"id": 58,
"fieldLabel": "Name Surname",
"providerLabel": "Name Surname",
"fieldName": "nmsrnm",
"fieldType": "text",
"fieldValue": null,
},
{
"id": 60,
"fieldLabel": "E-mail",
"providerLabel": "E-mail",
"fieldName": "e_mail_60",
"fieldType": "email",
"fieldValue": null,
},
{
"id": 2,
"fieldLabel": "Budget",
"providerLabel": "Budget",
"fieldName": "bdget",
"fieldType": "select",
"fieldValue": "",
"infoRequestFormOptions": [
{
"id": 1,
"orderNum": 0,
"optionValue": 0,
"optionText": "Select",
"minValue": null,
"maxValue": null
},
{
"id": 2,
"orderNum": 1,
"optionValue": 1,
"optionText": "10-30",
"minValue": 10,
"maxValue": 30
}
]
}
]

How to make multiple search filters work with a for loop in Vue Bootstrap?

I have a table with some filters in each column but when I type anything all the items disappear. The console does not return any error.
Here’s the code:
<template>
<div>
<b-table
id="the-table"
:per-page="perPage"
:current-page="currentPage"
:items="filteredItems"
:fields="fields"
>
<template slot="top-row" slot-scope="{ fields }">
<td v-for="field in fields" :key="field.key">
<input v-model="filters[field.key]" :placeholder="field.label" />
</td>
</template>
</b-table>
<b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage" aria-controls="the-table"></b-pagination>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
filters: {
option: "",
style: "",
stock: "",
},
items: [],
fields: [
{ key: "options", label: "Options", sortable: true },
{ key: "style", label: "Style", sortable: true },
{ key: "stock", label: "Stock", sortable: true },
{ key: "type", label: "Type", sortable: true },
{ key: "class", label: "Class.", sortable: true },
],
perPage: 15,
currentPage: 1,
};
},
created() {
this.getTable();
},
methods: {
getTable() {
axios
.get("./data/options.json")
.then((res) => (this.items = res.data))
.catch((error) => console.log(error));
},
},
computed: {
rows() {
return this.items.length;
},
filteredItems() {
return this.items.filter((d) => {
return Object.keys(this.filters).every((f) => {
return this.filters[f].length < 1 || this.filters[f].includes(d[f]);
});
});
},
},
};
</script>
I am trying to filter an array of objects like this:
[{"option": "ABEVH160", "style": "American", "stock": "ABEV3", "type": "CALL", "class": "ITM"},
{"option": "BBAS230", "style": "European", "stock": "BBAS3", "type": "PUT", "class": "ATM"},
{"option": "BBDC180", "style": "American", "stock": "BBDC4", "type": "CALL", "class": "OTM"}]
My goal is to be able to filter each of the columns individually:
Does anyone know what I’m missing?
The problem is with the condition:
return this.filters[f].length < 1 || this.filters[f].includes(d[f]);
d[f] is the full value and this.filters[f] is the search string. Obviously this does not work since it checks if the full word is contained in a substring. Simply invert the condition:
return this.filters[f].length < 1 || d[f].includes(this.filters[f]);
You can see it working here.
What you want seems to be something like DataTable Filter | Filter Row in PrimeVue. I tried to find something similar in the documentation of bootstrap-vue (documentation), but couldn´t find anything like that.
Maybe you are in a stage where you can still implement PrimeVue in your project. I´m using Filter Row from PrimeVue by myself and can recommend it.

Flickering of charts and getcontext error with chartjs in the context of Vuejs

Hello i am trying to display different charts using the chartjs by calling the API. Below code shows how i have formatted the chart.vue
Chart.vue:
<template>
<div class="chart-container" style="position: relative; height: 40vh; width:100%;">
<slot name="test1"></slot>
<slot name="test2"></slot>
</div>
</template>
<script>
export default {
name: 'charts',
data () {
return {
date: [],
challenge: [],
data: []
}
},
mounted () {
this.check(8, 'chart_8')
this.check(7, 'chart_7')
},
methods: {
check (id, name) {
this.$http.get(`/api_chart/${ id }/full`)
.then((response) => {
this.date = response.data.date
this.challenge = response.data.challenge
this.data = this.date.map((date, index) => ({
x: new Date(date * 1000),
y: this.challenge[index]
}))
const ctx = document.getElementById([name]).getContext('2d')
let myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'Challenge',
data: this.data,
borderColor: ' #EA5455',
}
]
},
options: {
lineTension: 0,
maintainAspectRatio: false,
scales: {
yAxes: [
{
scaleLabel: {
display: false
},
ticks: {
beginAtZero: true,
callback (value) {
return `${value}%`
}
}
}
],
xAxes: [
{
type: 'time',
time: {
unit: 'month'
},
scaleLabel: {
display: true,
}
}
]
}
}
})
})
}
}
}
</script>
App.vue:
<template>
<div class="In order to display chart1">
<chart-display> <canvas slot="test1" id="chart_7" ></canvas> </chart-display>
</div>
<div class="In order to display chart1">
<chart-display> <canvas slot="test2" id="chart_8" ></canvas> </chart-display>
</div>
</template>
<script>
import chart-display from './Chart.vue'
export default {
component: {chart-display}
}
</script>
As you can see i have shared my Chart.vue and App.vue, i am able to see my chart in the browser, but whenever i run the code or refresh the page, the charts flickers and stops. And then in my console i get below error:
Please someone help me to get rid of this issue, and please tell me if any changes i should do in my code to solve it. Please send me the modification code.
As I wrote in my comment, the charts are rendered twice. This causes flickering.
// every time you use <chart-display>, 2 charts are rendered, this means chart 1 renders
// itself and chart 2, char 2 renders itself and chart 1, this is a bad pattern in Vue in general
mounted() {
this.check(8, "chart_8");
this.check(7, "chart_7");
}
Make the following changes:
ChartDisplay.vue
<template>
<div
class="chart-container"
style="position: relative; height: 40vh; width: 100%"
>
<canvas ref="chart_7"></canvas>
<canvas ref="chart_8"></canvas>
</div>
</template>
<script>
import Chart from "chart.js";
export default {
name: "ChartDisplay",
data() {
return {
date: [],
challenge: [],
data: [],
// save charts in an array
charts: [],
// charts options
options: {
lineTension: 0,
maintainAspectRatio: false,
scales: {
yAxes: [
{
scaleLabel: {
display: false,
},
ticks: {
beginAtZero: true,
callback(value) {
return `${value}%`;
},
},
},
],
xAxes: [
{
type: "time",
time: {
unit: "month",
},
scaleLabel: {
display: true,
},
},
],
},
},
};
},
mounted() {
this.render(7, this.$refs.chart_7);
this.render(8, this.$refs.chart_8);
},
methods: {
render(id, ctx) {
this.fetchData(id).then((response) => {
let data = response.date.map((date, index) => ({
x: new Date(date * 1000),
y: response.challenge[index],
}));
this.charts.push(
new Chart(ctx, {
type: "line",
data: {
datasets: [
{
label: "Challenge",
data: data,
borderColor: " #EA5455",
},
],
},
options: this.options,
})
);
});
},
fetchData(id) {
return this.$http.get(`/api_chart/${ id }/full`);
},
},
beforeDestroy() {
this.charts.forEach((chart) => chart.destroy());
},
};
</script>
<style >
[v-cloak] {
display: none;
}
</style>
App.vue
<template>
<div>
<div class="In order to display chart1">
<chart-display/>
</div>
</div>
</template>
<script>
import ChartDisplay from "./ChartDisplay.vue";
export default {
components: { ChartDisplay },
};
</script>
See it on sandbox
I found several errors on your code. I fix them in Sandbox
For Chat.vue :
I rename the file as ChartDisplay.vue as similar as the component name
import chart.js package for using Chart() function
I use a demo API
<template>
<div
class="chart-container"
style="position: relative; height: 40vh; width: 100%"
>
<slot name="test1"></slot>
<slot name="test2"></slot>
</div>
</template>
<script>
import Chart from "chart.js";
export default {
name: "ChartDisplay",
data() {
return {
date: [],
challenge: [],
data: [],
};
},
mounted() {
this.check(8, "chart_8");
this.check(7, "chart_7");
},
methods: {
check(id, name) {
fetch(
"https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs"
)
.then((response) => response.json())
.then((response) => {
this.date = response.date;
this.challenge = response.challenge;
this.data = this.date.map((date, index) => ({
x: new Date(date * 1000),
y: this.challenge[index],
}));
const ctx = document.getElementById([name]).getContext("2d");
new Chart(ctx, {
type: "line",
data: {
datasets: [{
label: "Challenge",
data: this.data,
borderColor: " #EA5455",
}, ],
},
options: {
lineTension: 0,
maintainAspectRatio: false,
scales: {
yAxes: [{
scaleLabel: {
display: false,
},
ticks: {
beginAtZero: true,
callback(value) {
return `${value}%`;
},
},
}, ],
xAxes: [{
type: "time",
time: {
unit: "month",
},
scaleLabel: {
display: true,
},
}, ],
},
},
});
});
},
},
};
</script>
For App.vue
Your import should not carry any hyphen.
component should be components
render the component once to avoid flikering
<template>
<div>
<div class="In order to display chart1">
<chart-display>
<canvas slot="test1" id="chart_7"></canvas>
<canvas slot="test2" id="chart_8"></canvas>
</chart-display>
</div>
</div>
</template>
<script>
import ChartDisplay from "./ChartDisplay.vue";
export default {
components: {
ChartDisplay
},
};
</script>

Reinitialization error while using datatables in Angular 7 while pulling data from an API

I'm trying to pull data from an API and display it in DataTables. Code is as given below:
<table class="table display table-striped table-hover table-bordered row-border hover" [dtOptions]="dtOptions" datatable="" #dataTable></table>
JavaScript:
#ViewChild(DataTableDirective)
#ViewChild('dataTable') table;
datatableElement: DataTableDirective;
dataTable: any;
dtOptions: any;
message = '';
title = 'angulardatatables';
ngOnInit(): void {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 15,
processing: true,
responsive: true,
dom: 'Bfrtip',
'ajax': {
url: 'http://localhost:8080/incident',
type: 'GET'
},
columns: [
{
title: 'Incident',
data: 'number'
},
{
title: 'Product',
data: 'u_product'
},
{
title: 'Status',
data: 'incident_state'
}
]
};
this.dataTable = $(this.table.nativeElement);
this.dataTable.DataTable(this.dtOptions);
}
When I run that code, I get below error:
DataTables warning: table id=DataTables_Table_0 - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
I made sure that datatables for my node hasn't bee initialized already and I'm using technique given in this link and this link.
How can I fix this error?
Fixed it!
New code is:
<table class="table display table-striped table-hover table-bordered row-border hover" datatable [dtOptions]="dtOptions" datatable="" #dataTable>
</table>
JavaScript:
#ViewChild(DataTableDirective)
datatableElement: DataTableDirective;
message = '';
title = 'angulardatatables';
constructor(private router: Router) {}
dtOptions: DataTables.Settings = { };
ngOnInit(): void {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 15,
processing: true,
responsive: true,
dom: 'Bfrtip',
'ajax': {
url: 'http://localhost:8080/incident',
type: 'GET',
dataSrc: "result"
},
columns: [
{
title: 'Incident',
data: 'number'
},
{
title: 'Product',
data: 'u_product'
},
{
title: 'Status',
data: 'state'
}
]
};
}

Fail to retrieve data from jquery datatables

My snippets below shows a datatables example that has 3 rows, I have added an extra column in column definition "action" and I m setting its display/data via default content and render functions respectively.
every time I try to build an JSON data containing the column "action" val i fail. I added the cell click listener (disabled in this action) just to make sure that the data is stored in the API data collection and it is indeed, yet it fails to show up after building the values.
if you click "build vals" you will see how the "action" data is not included in JSON. if you click "Mark for delete" and then "build vals" the "action" data will show up.
any idea how to make it work?
var tablenest = $('#RegSrc').DataTable({
select: true,
"bPaginate": false,
"bFilter": false,
responsive: true,
deferRender: true,
"processing": true,
"serverSide": false,
bAutoWidth: true,
data: [{
"RecID": 2383,
"PtFilenum": 15090248,
"PrtFilenum": 13090701,
"Fullname": "Salem",
"PrtStatus": 1
}, {
"RecID": 2384,
"PtFilenum": 15090248,
"PrtFilenum": 15120996,
"Fullname": "Tony",
"PrtStatus": 1
}, {
"RecID": 2385,
"PtFilenum": 15090248,
"PrtFilenum": 170227111,
"Fullname": "Jorge",
"PrtStatus": 1
}],
order: [2, 'asc'],
keys: {
columns: ':not(:first-child)',
keys: [9]
},
columns: [
{ // Checkbox select column
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false,
"width": "1%"
},
{
"width": "50%",
data: "RecID",
"visible": false
},
{
"width": "50%",
data: "PtFilenum",
"visible": false
},
{
"width": "10%",
data: "PrtFilenum"
},
{
"width": "40%",
data: "Fullname"
},
{
"width": "10%",
data: "PrtStatus",
render: function(data, type, row) {
if (type === 'display') {
if (data == 1) {
return 'Partners';
} else {
return 'Not Partners';
}
}
return data;
},
className: "dt-body-center"
},
{
"width": "10%",
data: 'action',
defaultContent: 'update',
orderable: false,
className: "dt-body-center",
"visible": true,
render: function(data, type, row) {
if (data == null) {
return 'update';
} else {
return data;
}
}
},
],
});
/* $('#RegSrc tbody').on('click', 'td', function () {
console.log(tablenest.cell(this).data());
});*/
$("#btn1").click(function() {
tablenest.rows({
selected: true
}).every(function(rowIdx, tableLoop, rowLoop) {
tablenest.row(this).cell(rowIdx, 6).data('delete').draw()
var row = tablenest.row(this).node();
$(row).css('color', 'red').animate({
color: 'black'
});
});
return false;
})
$("#btn2").click(function() {
var tbldta = $.map(tablenest.rows().data(), function(d, i) {
var myObject = new Object();
myObject = {
action: d.action,
RecID: d.RecID,
PrtStatus: d.PrtStatus,
ptfilenum: d.PtFilenum,
PrtFilenum: d.PrtFilenum
}
return myObject
});
var DtaObj = {}
DtaObj.Data = tbldta
console.log(JSON.stringify(DtaObj))
return false;
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/v/dt/jqc-1.12.4/moment-2.18.1/dt-1.10.15/b-1.3.1/se-1.2.2/datatables.min.js"></script>
<button id="btn2" class="btn btn-primary">build vals</button>
<button id="btn1" class="btn btn-primary">Mark For Delete</button>
<table id="RegSrc" class="table table-bordered table-striped table-condensed mb-none display responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>click here to select</th>
<th><b>RecID</b></th>
<th><b>Patient File Number</b></th>
<th><b>Partner File Number</b></th>
<th><b>Patient Name</b></th>
<th><b>Status</b></th>
<th><b>action</b></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Include "action":"update" to your data source in constructor.
columns.defaultContent is static and therefore cannot possibly access
the data.
Also you can remove render from "action" column.
var tablenest = $('#RegSrc').DataTable({
select: true,
"bPaginate": false,
"bFilter": false,
responsive: true,
deferRender: true,
"processing": true,
"serverSide": false,
bAutoWidth: true,
data: [{
"RecID": 2383,
"PtFilenum": 15090248,
"PrtFilenum": 13090701,
"Fullname": "Salem",
"PrtStatus": 1,
"action": "update"
}, {
"RecID": 2384,
"PtFilenum": 15090248,
"PrtFilenum": 15120996,
"Fullname": "Tony",
"PrtStatus": 1,
"action": "update"
}, {
"RecID": 2385,
"PtFilenum": 15090248,
"PrtFilenum": 170227111,
"Fullname": "Jorge",
"PrtStatus": 1,
"action": "update"
}],
order: [2, 'asc'],
keys: {
columns: ':not(:first-child)',
keys: [9]
},
columns: [
{ // Checkbox select column
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false,
"width": "1%"
},
{
"width": "50%",
data: "RecID",
"visible": false
},
{
"width": "50%",
data: "PtFilenum",
"visible": false
},
{
"width": "10%",
data: "PrtFilenum"
},
{
"width": "40%",
data: "Fullname"
},
{
"width": "10%",
data: "PrtStatus",
render: function(data, type, row) {
if (type === 'display') {
if (data == 1) {
return 'Partners';
} else {
return 'Not Partners';
}
}
return data;
},
className: "dt-body-center"
},
{
"width": "10%",
data: 'action',
orderable: false,
className: "dt-body-center",
"visible": true
},
],
});
/* $('#RegSrc tbody').on('click', 'td', function () {
console.log(tablenest.cell(this).data());
});*/
$("#btn1").click(function() {
tablenest.rows({
selected: true
}).every(function(rowIdx, tableLoop, rowLoop) {
tablenest.row(this).cell(rowIdx, 6).data('delete').draw()
var row = tablenest.row(this).node();
$(row).css('color', 'red').animate({
color: 'black'
});
});
return false;
})
$("#btn2").click(function() {
var tbldta = $.map(tablenest.rows().data(), function(d, i) {
var myObject = new Object();
console.log(d);
myObject = {
action: d.action,
RecID: d.RecID,
PrtStatus: d.PrtStatus,
ptfilenum: d.PtFilenum,
PrtFilenum: d.PrtFilenum
}
return myObject
});
var DtaObj = {}
DtaObj.Data = tbldta
console.log(JSON.stringify(DtaObj))
return false;
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/v/dt/jqc-1.12.4/moment-2.18.1/dt-1.10.15/b-1.3.1/se-1.2.2/datatables.min.js"></script>
<button id="btn2" class="btn btn-primary">build vals</button>
<button id="btn1" class="btn btn-primary">Mark For Delete</button>
<table id="RegSrc" class="table table-bordered table-striped table-condensed mb-none display responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>click here to select</th>
<th><b>RecID</b></th>
<th><b>Patient File Number</b></th>
<th><b>Partner File Number</b></th>
<th><b>Patient Name</b></th>
<th><b>Status</b></th>
<th><b>action</b></th>
</tr>
</thead>
<tbody>
</tbody>
</table>