Adding class to p tags throws eslint error - vue.js

I am working on a project and integrating Vue within it. There's eslint and vues eslint included with the webpack compiler. When I try to compile the code, I get an error cannot read property 'replace' of undefined. This appears whenever I try to add a <p> tag with any sort of attribute to it. Looking at the code below <p class="name">John Smith</p> will throw the error. If I remove it, the error's gone.
I'm not using replace anywhere within the file, so I'm not sure why eslint would be throwing this error, or how to get past it.
Component file
<template>
<div v-if="committee_id > 0">
<a
href="#"
class="line-btn blue"
><span>Return to the section's committees list</span></a>
<h2>{{ data.title }}</h2>
<div
v-html="data.content"
></div>
<div class="btn-cnt">
<a
href="#"
class="curve-btn blue"
#click.prevent="goBack"
><span>Join the committee</span></a>
</div>
<div class="roster detail-roster">
<h3>Committees Roster</h3>
<div class="row">
<div class="col-xs-6">
<p class="name">John Smith</p>
</div>
</div>
</div>
</div>
</template>
<script>
import {EventBus} from '../event-bus';
import axios from 'axios';
export default {
data() {
return {
classArray: {
name: 'name',
title: 'title',
},
committee_id: 0,
data: [],
api_url: (API.restUrl !== undefined) ? API.restUrl : '',
};
},
created() {
EventBus.$on('committee-post-id', committee_id => {
this.committee_id = committee_id;
this.getCommitteePost();
});
},
methods: {
getCommitteePost: () => {
this.$nextTick(function () {
axios.get(`${this.api_url + this.committee_id}`)
.then(({data}) => {
if (data.message === 'success') {
this.$nextTick(function () {
this.data = data;
});
}
})
.catch(err => {});
});
},
goBack: () => {
}
},
name: 'section-committee'
};
</script>
Eslint
module.exports = {
"root": null,
"globals": {
"wp": true
},
"env": {
"node": true,
"es6": true,
"amd": true,
"browser": true,
"jquery": true
},
'extends': [
'plugin:vue/recommended'
],
"parserOptions": {
"ecmaFeatures": {
"globalReturn": true,
"generators": false,
"objectLiteralDuplicateProperties": false,
"experimentalObjectRestSpread": true
},
"ecmaVersion": 2017,
"sourceType": "module"
},
"plugins": [
"import"
],
"settings": {
"import/core-modules": [],
"import/ignore": [
"node_modules",
"\\.(coffee|scss|css|less|hbs|svg|json)$"
]
},
"rules": {
"no-console": 0
}
}

Unsure still what's going on, but a resolution for the linter was to change the following in my linter file.
'extends': [
'plugin:vue/base'
],

Related

Default props value are not selected in vue3 options api

I created a select2 wrapper in vue3 with options API everything working fine but the problem is that when getting values from calling API it's not selected the default value in the select2 option. but when I created a static array of objects it does. I don't know why it's working when it comes from the API
Parent Component
Here you can I passed the static options array in options props and my selected value is 2 and it's selected in my Select2 component, but when passed formattedCompanies it's not which is the same format as the static options array then why is not selected any reason here..?
<template>
<Form #submitted="store()" :processing="submitting">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Company Name</label>
<Select2
:options="options"
v-model="selected"
placeholder="Select Company"
/>
<ValidationError :errors="errors" error-key="name" />
</div>
</div>
</div>
</Form>
</template>
<script>
import Form from "#/components/Common/Form";
import Select2 from "#/components/Common/Select2";
export default {
components: {
Select2,
Form
},
data() {
return {
selected : 2,
companies : [],
options: [ // static array
{ id: 1, text: 'hello' },
{ id: 2, text: 'hello2' },
{ id: 3, text: 'hello3' },
{ id: 4, text: 'hello4' },
{ id: 5, text: 'hello5' },
],
}
},
mounted() {
this.getAllMedicineCompanies()
},
computed:{
formattedCompanies() {
let arr = [];
this.companies.forEach(item => {
arr.push({id: item.id, text: item.name})
});
return arr;
}
},
methods: {
getAllMedicineCompanies(){
axios.get('/api/get-data?provider=companies')
.then(({ data }) => {
this.companies = data
})
},
}
}
</script>
Select2 Component
Here is what my select2 component look like, did I do anything wrong here, please anybody help me
<template>
<select class="form-control">
<slot/>
</select>
</template>
<script>
export default {
name: "Select2",
props: {
options: {
type: [Array, Object],
required: true
},
modelValue: [String, Number],
placeholder: {
type: String,
default: "Search"
},
allowClear: {
type: Boolean,
default: true
},
},
mounted() {
const vm = this;
$(this.$el)
.select2({ // init select2
data: this.options,
placeholder: this.placeholder,
allowClear: this.allowClear
})
.val(this.modelValue)
.trigger("change")
.on("change", function () { // emit event on change.
vm.$emit("update:modelValue", this.value);
});
},
watch: {
modelValue(value) { // update value
$(this.$el)
.val(value)
.trigger("change");
},
options(options) { // update options
$(this.$el)
.empty()
.select2({data: options});
},
},
destroyed() {
$(this.$el)
.off()
.select2("destroy");
}
}
</script>
Probably when this Select2 mounted there is no companies. It is empty array after that it will make API call and it it populates options field and clear all options.
Make:
companies : null,
Change it to
<Select2
v-if="formattedCompanies"
:options="formattedCompanies"
v-model="selected"
placeholder="Select Company"
/>
It should be like this:
<template>
<Form #submitted="store()" :processing="submitting">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Company Name</label>
<Select2
v-if="formattedCompanies"
:options="formattedCompanies"
v-model="selected"
placeholder="Select Company"
/>
<ValidationError :errors="errors" error-key="name" />
</div>
</div>
</div>
</Form>
</template>
<script>
import Form from "#/components/Common/Form";
import Select2 from "#/components/Common/Select2";
export default {
components: {
Select2,
Form
},
data() {
return {
selected : 2,
companies : null,
options: [ // static array
{ id: 1, text: 'hello' },
{ id: 2, text: 'hello2' },
{ id: 3, text: 'hello3' },
{ id: 4, text: 'hello4' },
{ id: 5, text: 'hello5' },
],
}
},
mounted() {
this.getAllMedicineCompanies()
},
computed:{
formattedCompanies() {
let arr = [];
this.companies.forEach(item => {
arr.push({id: item.id, text: item.name})
});
return arr;
}
},
methods: {
getAllMedicineCompanies(){
axios.get('/api/get-data?provider=companies')
.then(({ data }) => {
this.companies = data
})
},
}
}
</script>
The problem was that my parent component and Select2 component mounted at the same time that's why my computed value is not initialized so the selected value is not selected in the option,
problem solved by setTimeOut function in mounted like this
Select2 Component
<script>
mounted() {
const vm = this;
setTimeout(() => {
$(this.$el)
.select2({ // init select2
data: this.options,
placeholder: this.placeholder,
allowClear: this.allowClear
})
.val(this.modelValue)
.trigger("change")
.on("change", function () { // emit event on change.
vm.$emit("update:modelValue", this.value);
});
}, 500)
},
</script>

datatable vueJS don´t show data

I´m trayin integrate datatable in my component vue. For this i´m using this library:
https://jamesdordoy.github.io/
i´m install in my proyect, i has configured it, created my component and include in my view, but returned me this message:
Invalid prop: type check failed for prop "data". Expected Object, got Array
my component it´s:
<template>
<div>
<div class="row justify-content-center w-100">
<data-table :data="data" :columns="columns" #on-table-props-changed="reloadTable"></data-table>
</div>
</div>
</template>
<script>
export default {
data() {
return {
url: "/admin/vue/getAllUsers",
data: {},
tableProps: {
search: '',
length: 10,
column: 'id',
dir: 'asc'
},
columns: [
{
label: 'ID',
name: 'id',
orderable: true,
},
{
label: 'Name',
name: 'name',
orderable: true,
},
{
label: 'Email',
name: 'email',
orderable: true,
},
]
}
},
created() {
this.cargar(this.url);
},
methods:{
cargar(url = this.url, options = this.tableProps){
axios.get(url, { params: options })
.then((response) => {
this.data = response.data;
})
.catch((error) => console.error(error));
},
reloadTable(tableProps) {
this.cargar(this.url, tableProps);
}
},
}
</script>
i was trayed with response.data[0] the error disappear but my table it´s empty, i don´t know that i´m doing wrong.
In my controller i have this:
return User::all();
i´m working with laravel 8
thanks for help
you should pass props :items = "data" instead of :data = "data"

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>

ag-Grid does not support .vue component as cellRenderer?

So I have this itemlist.vue file
<div>
<div>
<ag-table
style=" height: 650px;"
class="ag-theme-balham"
:column-defs="columnDefs"
:row-data="rowData"
/>
</div>
</div>
</template>
<script>
import AgTable from "../components/AgTable";
import editRenderer from "../components/AgGridRenderers/editDeleteRenderer.vue";
export default {
components: {
AgTable
},
data: () => ({
users: [],
columnDefs: null,
rowData: null,
editR: editRenderer
}),
mounted () {
this.columnDefs = [
{ headerName: "Name", field: "name", sortable: true, filter: true },
{ headerName: "e-Mail", field: "email", sortable: true, filter: true },
{ headerName: "Contact", field: "contact", sortable: true, filter: true },
{ headerName: "Contact", field: "contact", sortable: true, filter: true, cellRenderer: editRenderer }
];
this.rowData = [
{ name: "Robin Sharma", email: "robin#sharma.com", contact: 8508035076 },
{ name: "Amish Tripathi", email: "amish#tripathi.com", contact: 9250035054 },
{ name: "Zig Ziglar", email: "zig#ziglar.com", contact: 9206635030 },
{ name: "Paulo Coelho", email: "paolo#coelho.com", contact: 7288012335 }
];
},
methods: {
loadUsers () {
// console.log("Loading Users from api.");
}
}
};
</script>
And index.vue file for Ag grid table as
<template>
<div>
<ag-grid-vue
style=" height: 650px;"
class="ag-theme-balham"
:column-defs="_props.columnDefs"
:row-data="_props.rowData"
:framework-components="frameworkComponents"
/>
</div>
</template>
<script>
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css";
import { AgGridVue } from "ag-grid-vue";
import editRenderer from "../AgGridRenderers/editDeleteRenderer.vue";
export default {
components: {
AgGridVue
},
props: [
"column-defs", "row-data"
],
data: () => ({
frameworkComponents: {
editRenderer
}
}),
mounted () {
console.log(this._props.columnDefs, this._props.rowData);
}
};
</script>
And editrenderer.vue file as:
<template>
<div>
<span>
<button #click="sayHi"> Edit Item </button>
</span>
</div>
</template>
<script>
export default {
created () {
console.log("Hello from Edit");
},
methods: {
sayHi () {
alert("Hi");
}
}
};
</script>
And all I am getting in the DOM is empty edit-renderer tags
Doesn't AgGrid support cellRenderers in Vue Js?
In the end the imported component appears as a vue component in the Dom if used separately as a common Dom element. Does that mean we explicitly have to compile it somehow? I also tried using setTimeOut before initializing columnDefs and rowData where AgTable is used. but still it doesn't show anything in the table.
Ok, so what I did was add some missing properties to ag-grid-vue element such as grid-options, context and grid-ready, and add refresh function to the renderer component, and convert all related components from simple "export default{" to "export default Vue.extends({".
I think this problem was resolved.
Though, I am getting 'this is undefined' error now.
Ag-grid should clarify which parameters are compulsory other than rowData and colDefs with their purpose.

how can I update progress bar when json data change using vue.js without refresh

I try to make a boostrap dashboard page for tracing status of my python aplication running on server.
On server side, python app update data.json file when reach certain status.
On client side, vue.js handle content creation.
I have a problem when I try to update progress bar, because i need to refresh page so that progress appears.
Any suggestion how can I make live progress bar in my view without refresh?
index.html
<div class="item" v-for="item in order">>
<div class="progress">
<div class="progress-bar bg-warning" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" :style="{ width: item.completion + '%' }">
</div>
</div>
</div>
app.js
window.addEventListener('load', () => {
window.vue = new Vue({
el: '#app',
name: 'Order',
data: {
isLoading: true,
order: [],
},
created() {
fetch('./data.json')
.then((res) => { return res.json() })
.then((res) => {
this.isLoading = false;
this.order = res.order;
})
}
})
});
data.json
{
"order": [
{
"customer": "Mr. Smith",
"price": "60",
"status": "Pending",
"orders": "Something",
"completion": 40,
"isAvailable": true,
"isEligible": true
}
]
}
edit: I solve my issue with adding watcher to app.js
watch: {
order() {
this.updateorder();
}
},
methods: {
updateorder() {
fetch('./data.json?_timestamp=' + Date.now())
.then((res) => { return res.json() })
.then((res) => {
this.order = res.order;
})
Does it help?
let i = 0;
const emulateRequest = () => Promise.resolve({
"order": [
{
"customer": "Mr. Smith",
"price": "60",
"status": "Pending",
"orders": "Something",
"completion": i++,
"isAvailable": true,
"isEligible": true
}
]
});
new Vue({
el: '#app',
data: () => ({
isLoading: true,
order: [],
}),
created() {
this.load();
},
methods: {
load() {
//fetch('./data.json')
// .then((res) => { return res.json() })
emulateRequest()
.then((res) => {
this.isLoading = false;
this.order = res.order;
if (this.order.some(({ completion }) => completion !== 100)) {
setTimeout(() => {
this.load();
}, 1000);
}
})
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div id="app">
<div class="item" v-for="item in order">
<div class="progress">
<div class="progress-bar bg-warning" role="progressbar" :aria-valuenow="item.completion" aria-valuemin="0" aria-valuemax="100" :style="{ width: `${item.completion}%` }">
</div>
</div>
</div>
</div>