No data available issue In JQuery Data table With VueJs - vue.js

I'm developing a system using C# and Vue Js, I need to show some data in table, for that I have use JQuery Data Table.
In my case all the data and options (search and pagination) is showing but problem is in table's top row showing as "No data available in Table" if we do force (Ctrl + F5) refresh then table is working perfectly.
Note : I searched regarding this problem in stack overflow there were some related questions I tried with those but I couldn't figure it out.
Please help me to resolve this problem.
1) after the first page load table is showing like this.
Note :If I searched something in search bar all data get not apear.
2) after force refresh table is showing like this and working perfectly.
This is the code's I have use for the implementation.
Vue Component.
Vue.component('all-enquiry', {
template: ' <table id="allenquiry" class="table table-striped table-bordered" cellspacing="0" style="width:100% !important"><thead><tr><th>Date<small>/Time</small></th><th>Hndle.By</th><th>Ref:No</th><th>Name</th><th>Destination</th><th>Dep.Date</th><th>Ret.Date</th><th>Airline</th><th>Status</th><th class="disabled-sorting text-right">Actions</th></tr></thead><tbody class="tbody-text"><tr v-for="enq in enquiryall"><td>{{ enq.CreatedDate | formatDate }}</td><td>{{ enq.HandleBy }}</td><td>{{ enq.EnqRefno }}</td><th>{{ enq.PaxName }}</th><td>{{ enq.DepartingTo }}</td><td>{{ enq.DepartingDate }}</td><td>{{ enq.ReturnDate }}</td><td>{{ enq.Airline }}</td><td><button class="btn btn-info btn-sm btn-round">Following Up</button></td><td class="text-right"><button class="btn btn-success btn-sm btn-round">More Info</button></td></tr></tbody></table >',
data() {
return {
enquiryall: '',
}
},
created: function () {
this.getall();
},
methods: {
getall: function () {
var enquiryform = this
axios.get("/Main/getAllenq/").then(function (response) {
enquiryform.enquiryall = response.data.allenquiry;
});
}
}
});
Table Initialization.
$(document).ready(function () {
$('#allenquiry').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
}
});
});
Html
<div class="card-body">
<div class="toolbar">
</div>
<all-enquiry></all-enquiry>
</div>

Maybe your ajax request not finished when you initialize the DataTables. Create an other method in the component to initialize the datatables. eg: initDt() {}
Because of the nextTick() it's going to initialize the DataTables when the table render finished.
Code not tested, it should have problems with the scopes, i'm using arrow () => {} functions instead of function().
Vue.component('all-enquiry', {
template: '...',
data() {
return {
enquiryall: '',
}
},
created: function () {
this.getall();
},
methods: {
getall: function () {
var enquiryform = this
axios.get("/Main/getAllenq/").then(function (response) {
enquiryform.enquiryall = response.data.allenquiry;
enquiryform.$nextTick(function() {
enquiryform.initDt()
});
});
},
initDt() {
$('#allenquiry').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
}
});
}
}
});

Use axios on mounted and create datatable on updated life-cycle method
mounted(){
axios
.get('/estimator')
.then(response => {
this.items = response.data;
// console.log(response.data);
})
},
updated(){
var datatable = $('#datatable').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search estimator",
}
});
}

Related

Vue-chartjs not rendering chart until page resize

I am using vue-chartjs to create charts for my application. I am passing the chartData as a prop. My chart doesn't render at first but does when I resize the window. Here is my code. First the chart component:
<script>
import { Doughnut, mixins } from "vue-chartjs";
const { reactiveProp } = mixins;
export default {
extends: Doughnut,
mixins: [reactiveProp],
mounted() {
this.render();
},
methods: {
render() {
console.log(this.chartData)
let options = {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false,
},
};
this.renderChart(this.chartData, options);
},
},
};
</script>
Now here is the code from the component where the chart is displayed:
template part
<v-container>
<ProjectDoughnutChart :chart-data="chartData" />
</v-container>
script part
components: {
ProjectDoughnutChart,
},
data() {
return {
chartData: {
labels: [],
datasets: [
{
backgroundColor: [],
hoverBackgroundColor: [],
data: [],
},
],
},
};
},
setChartsTimesheets() {
this.timesheets.forEach((timesheet) => {
let typeTotal = 0;
this.timesheets
.filter((timesheet1) => timesheet1.type==timesheet.type)
.forEach((timesheet1) => {
typeTotal+=timesheet1.billableAmount;
});
if (this.chartData.labels.indexOf(timesheet.type) === -1) {
let colors = this.getTaskColors(timesheet.type);
this.chartData.labels.push(timesheet.type);
this.chartData.datasets[0].data.push(typeTotal);
this.chartData.datasets[0].backgroundColor.push(colors.color);
this.chartData.datasets[0].hoverBackgroundColor.push(colors.hover);
}
});
},
Solved the problem using a similar solution as "Chart with API data" from the documentation.
TL;DR: Adding a v-if on the chart
For people, that have similar problem, but not using vue.js or the official solution doesnt cut it. I had to chart.update() the graph to show values, that were added after the graph was created.
See the example. If you comment the chart.update() line, the graph will not refresh until the window is resized.
let chart = new Chart(document.getElementById("chart"), {
type: "line",
data: {
labels: ["a", "b", "c", "d", "e", "f"],
datasets: [{
label: 'Dataset 1',
data: [1, 5, 12, 8, 2, 3],
borderColor: 'green',
}]
},
options: {
interaction: {
mode: 'index',
intersect: true,
},
stacked: false,
responsive: true,
}
});
// adding data to graph after it was created (like data from API or so...)
chart.data.labels.push("new data");
chart.data.datasets[0].data.push(9);
// with chart.update(), the changes are shown right away
// without chart.update(), you need to resize window first
chart.update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="chart"></canvas>

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>

How to use google data-table chart in vuejs project?

In my vuejs project how to use google data-table chart? Google data-table chart link given below:
https://developers.google.com/chart/interactive/docs/gallery/table
I can implement this chart in normal javascript code. But how to use in vuejs code.
You can use your own component. Here I have made one simple example.
Vue.component('google-data-table', {
template: `<div id='app' ref="table_div"></div>`,
props: {
columns: {
type: Array,
required: true
},
tableData: {
type: Array,
required: true
}
},
mounted() {
google.charts.load('current', {
'packages': ['table']
});
google.charts.setOnLoadCallback(this.drawTable);
},
methods: {
drawTable: function() {
var data = new google.visualization.DataTable();
this.columns.forEach(element => {
data.addColumn(element.type, element.title);
});
data.addRows(this.tableData);
var table = new google.visualization.Table(this.$refs.table_div);
table.draw(data, {
showRowNumber: true,
width: '100%',
height: '100%'
});
}
}
});
new Vue({
el: '#app',
data: {
columns: [{
type: 'string',
title: 'Name'
},
{
type: 'number',
title: 'Salary'
},
{
type: 'boolean',
title: 'Full Time Employee'
}
],
tableData: [
['Mike', {
v: 10000,
f: '$10,000'
}, true],
['Jim', {
v: 8000,
f: '$8,000'
}, false],
['Alice', {
v: 12500,
f: '$12,500'
}, true],
['Bob', {
v: 7000,
f: '$7,000'
}, true]
]
}
});
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</head>
<body>
<div id="app">
<google-data-table :columns='columns' :table-data='tableData' />
</div>
</body>
</html>

How should data be structured for lineplots with vue/chart.js

I am retrieving data from an api (working) and generating a line plot with vue-chartjs.
However only the first two points are plotted. I must have my data structured in the wrong way but I don't know what it is expecting.
Here is my component:
import { Line } from "vue-chartjs";
export default {
extends: Line,
props: {
chartdata: {
type: Object,
default: null
}
},
mounted() {
this.renderChart(this.chartdata);
}
};
And in my App.vue file, I have this simple template:
<template>
<div id="app">
<div class="container">
<div class="Chart">
<h2>LineChart</h2>
<line-chart v-if="loaded" :chartdata="chartdata"></line-chart>
</div>
</div>
</div>
</template>
and this script:
<script>
import LineChart from './components/LineChart.js'
export default {
name: 'app',
components: { LineChart },
data:() => ({
loaded: false,
chartdata: null
}),
async mounted () {
this.loaded = false;
try {
let mydata = await fetch("http://myserver00/api/load/myserver02")
.then(stream => stream.json())
.then(mydata => {
let usercpu = [];
mydata.forEach(record => {
usercpu.push( record.cpu.user );
});
this.usercpu = usercpu;
});
} catch (e) {
console.error(e)
}
this.loaded = true;
this.chartdata = {
datasets: [
{label: 'CPU', data: this.usercpu}
]
};
}
}
</script>
As you may notice, I'm trying to system data from psutils to monitor servers. The original record from the api has several fields. This example just shows my attempt at CPU usage.
The browser tools show the data I expect, but apparently not what the chart expects. Here's a view of the data from the chrome vue devtools extension
Edit: to make sure the data is actually loaded, I added {{chartdata}} into my template and I see it all. Here is how it starts, the array goes on with all the data array. And the actual plot again shows only the first two data points.
{ "datasets": [ { "label": "CPU", "data": [ 2.7, 2.9, 3
Finally got it; I needed to re-read the doc for Chartjs. So here's the mounted function now. See that I had to put in x and y values for each point.
async mounted () {
this.loaded = false;
try {
let usercpu = [];
await fetch("http://server/api/load/server02")
.then(stream => stream.json())
.then(mydata => { mydata.forEach(record => {
usercpu.push( { y: record.cpu.user, x: record.date });});});
this.loaded = true;
this.chartdata = {
datasets: [ {
fill: false,
pointRadius: 0,
borderWidth: 2,
label: 'CPU',
data: usercpu
} ] };
} catch (e) {
console.error(e)
}
}
Also, in the data portion of the default function I had to add axes. I'm not exactly sure why, but even when the data was okay (above) I still couldn't see the plot. So when I added the axes, there everything was:
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: "hour",
displayFormats: {
hour: "M/DD # hA"
},
tooltipFormat: "MMM. DD # hA"
},
scaleLabel: {
display: true,
labelString: "Date/Time"
},
ticks: { autoSkip: true, maxTicksLimit: 5},
position: 'bottom'
}],
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 10
}
}]
}
And of course I had to include the options in the directive:
<template>
<div id="app">
<div class="container">
<div id="cpu">
<h2>Server02</h2>
<line-chart v-if="loaded" :chartdata="chartdata" :options="options"></line-chart>
</div>
</div>
</div>
</template>

Vue-Slick and v-for with dynamic data

i'm using vue-slick to show my images..
i've tried every solution that i found.. but none is working.
here is my template:
<slick ref="slick" :options="slickOptions">
<img v-for="(item) in categories" :src="'/images/category/'+item.image_url" alt="" class="img-fluid" >
</slick>
and here is my scripts:
data () {
return {
categories:'',
slickOptions: {
dots: true,
infinite: false,
autoplay: false,
arrows : false,
draggable:true,
speed: 1000,
slidesToShow: 1,
slidesToScroll: 1,
},
}
},
mounted() {
let _this = this;
axios({
method: 'post',
url: '/api/category',
data : {'name' : _this.name}
}).then( (response)=> {
console.log(response.data.data);
_this.categories = response.data.data;
}).catch((error) => {
console.log(error.response)
});
},
methods:{
next() {
this.$refs.slick.next();
},
prev() {
this.$refs.slick.prev();
},
reInit() {
this.$refs.slick.reSlick()
}
},
and only loading the image, and the slick is not working...!!?
I have faced the same issue, and what I did to solve this is to put the
v-if="categories.length > 0" on the <slick> tag.
It make the slick won't be created before the data that we want to display contains the data first.
Use below code to reinit slick, and call on success function of response
reInit() {
let currIndex = this.$refs.slick.currentSlide()
this.$refs.slick.destroy()
this.$nextTick(() => {
this.$refs.slick.create()
this.$refs.slick.goTo(currIndex, true)
})
}
I'm assuming your Axios is returning data with the structure you are looking for.
I'm also assuming you are using the vue-slick component and not slick.
You should iterate through a DIV like stated in the documentation. Without Axios, I did this:
In template:
<slick ref="slick" :options="slickOptions">
<div>Escolhe uma configuraĆ§Ć£o...</div>
<div v-for="d in data1"><a class="inline" :href="d.image"><img :src="d.image" alt="">{{ d.text }}</a></div>
</slick>
In Javascript:
data: function() {
return {
data1: [
{ image: 'http://placehold.it/100x100', text: 'Config1' },
{ image: 'http://placehold.it/100x100', text: 'Config2' },
{ image: 'http://placehold.it/100x100', text: 'Config3' },
{ image: 'http://placehold.it/100x100', text: 'Config4' }
]
}