Uncaught ReferenceError: then is not defined in Element Ui Plus - vue.js

I'm using the vue3 and element-ui-plus to build a project.
But when I tried to use the MessageBox in element-ui-plus, there was an error Uncaught ReferenceError: then is not defined coming out.
Other functions are good except MessageBox.
Here is my code. And Please refer to the handleDelete function.
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
const app ={
el: '#app',
data(){
return {
pagination: {
currentPage: 1,
pageSize: 10,
total: 0,
queryString: null
},
formData: {},
}
},
created() {
this.findPage();
},
methods: {
findPage() {
var param = {
currentPage: this.pagination.queryString == null ? this.pagination.currentPage : 1,
pageSize: this.pagination.pageSize,
queryString: this.pagination.queryString
};
axios.post("/checkitem/findPage.do",param).then(res => {
this.pagination.total = res.data.total;
this.dataList = res.data.rows;
});
},
resetForm() {
this.formData = {};
},
handleDelete(row) {
this.$confirm("Do you want to delete the record?","Warning",{
confirmButtonText: "Yes",
cancelButtonText: "No",
type: "warning"
}).then(() => {
console.log("delete record");
axios.get("/checkitem/delete.do?id="+row.id).then(res => {
});
}).catch(() => {
});
}
}
};
Vue.createApp(app).use(ElementPlus).mount("#app");
<script>

#Oliver you could try making your function async. See below
async handleDelete(row) {
try {
await this.$confirm("Do you want to delete the record?","Warning",{
confirmButtonText: "Yes",
cancelButtonText: "No",
type: "warning"
})
console.log("delete record")
axios.get("/checkitem/delete.do?id="+row.id)
} catch (error) {
// handle error
} finally {
// something else if you need
}
})
Question though, are you meant to be waiting for a user to confirm/cancel the click before you trigger execute the delete?

Related

Apexchats.js axios gives me undefined with Vue

I am trying to get data from server using vue and apexcharts, but even after I called data with axios, it gives me undefined..
What have I missed?
template
<apexchart
ref="chart1"
width="100%"
:options="chartOptions" :series="series">
</apexchart>
data from url
{
"pageviews": 1313,
"new_users": 1014
}
script
export default {
data: function () {
return {
series: [],
chartOptions: {
chart: {
type: 'donut',
},
colors: ['#01cd49', '#007568'],
labels: ['new', 're'],
}
},
created: function () {
this.getByVisitor()
},
methods: {
getByVisitor() {
const url = 'url';
axios
.get(url)
.then(response => {
this.$refs.chart1.updateSeries([{
name: 'Sales',
data: response.data
}])
})
.catch(error => (this.byVisitor = error.data));
console.log(`---------------this.$refs.chart1`, this.$refs.chart1);
},
}
See Updating Vue Chart Data
There's no need to directly call the updateSeries() method on the chart component since it is able to react to changes in series. All you have to do is update your series data property
export default {
data: () => ({
series: [], // 👈 start with an empty array here
byVisitor: null, // 👈 you seem to have missed this one for your error data
chartOptions: {
chart: {
type: 'donut',
},
colors: ['#01cd49', '#007568'],
labels: ['new', 're'],
}
}),
created: function() {
this.getByVisitor()
},
methods: {
async getByVisitor() {
const url = 'url';
try {
const { data } = await axios.get(url)
// now update "series"
this.series = [{
name: "Sales",
data
}]
} catch (error) {
this.byVisitor = error.data
}
},
}
}

Vue PayPal implementation with vue-head, paypal not defined

I'm trying to add the paypal sdk via vue-head(https://www.npmjs.com/package/vue-head) in my component but I keep getting this error:
Error in mounted hook: "ReferenceError: paypal is not defined"
What am I doing wrong here? Is the SDK simply not loading before mounted?
Is there a better way to accomplish this? Does anyone have an example of their paypal implementation in vue? Any help would be greatly appreciated.
edit: Also if I include the script tag server side (rails) then try to access paypal in vue I see this error:
Could not find driver for framework: [object Object]
<template>
<div id="paypal-button" />
</template>
<script>
import { mapState as mapConfigState } from '../scripts/store/appConfig';
export default {
props: {
totalPrice: {
type: String,
required: true,
},
currency: {
type: String,
required: true,
'default': 'USD',
},
buttonStyle: {
type: Object,
required: false,
},
},
computed: {
...mapConfigState({
customer: state => state.customer,
}),
paypalEnvironment() {
return (this.customer.paypalTestingMode) ? 'sandbox' : 'production';
},
client() {
return {
sandbox: this.customer.paypalClientIdSandbox,
production: this.customer.paypalClientIdLIVE,
};
},
},
head: {
script() {
return [
{
type: 'text/javascript',
src: `https://www.paypal.com/sdk/js?client-id=${this.client[this.paypalEnvironment]}`,
},
];
},
},
mounted() {
const total = this.totalPrice;
const currency = this.currency;
paypal.Buttons.driver(
{
env: this.paypalEnvironment,
client: this.client,
style: this.buttonStyle,
createOrder(data, actions) {
return actions.order.create({
purchase_units: [
{
amount: {
value: total,
currency,
},
},
],
});
},
onApprove(data, actions) {
return actions.order.capture();
},
}, '#paypal-button'
);
},
};
</script>
edit2: I tried adding the script in my mounted hook like this:
let el = document.querySelector(`script[src="https://www.paypal.com/sdk/js?client-id=${this.client[this.paypalEnvironment]}"]`);
if (!el) {
const src = `https://www.paypal.com/sdk/js?client-id=${this.client[this.paypalEnvironment]}`;
el = document.createElement('script');
el.type = 'text/javascript';
el.async = true;
el.src = src;
document.head.appendChild(el);
}
I can see the script in the head tag in the dev console but paypal still is not defined.
For anyone else who is trying to implement PayPal in a Vue component:
<template>
<div id="paypal-button" />
</template>
<script>
export default {
mounted() {
function loadScript(url, callback) {
const el = document.querySelector(`script[src="${url}"]`);
if (!el) {
const s = document.createElement('script');
s.setAttribute('src', url); s.onload = callback;
document.head.insertBefore(s, document.head.firstElementChild);
}
}
loadScript('https://www.paypal.com/sdk/js?client-id=sb&currency=USD', () => {
paypal.Buttons({
// Set up the transaction
createOrder(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01',
},
}],
});
},
// Finalize the transaction
onApprove(data, actions) {
return actions.order.capture().then(details => {
// Show a success message to the buyer
alert(`Transaction completed by ${details.payer.name.given_name}`);
});
},
}).render('#paypal-button');
});
},
};
</script>
Alternatively you can use this: https://github.com/paypal/paypal-js

Vue-Tables-2 Side Server Get Error " Cannot read property 'data' of undefined" Why?

I am using vue-tables-2 for manage data. I wanna implement server side. But I got a problem. I can get the data as well. But I dont know why I got that error message. This is my code:
HTML
<v-server-table :columns="columns" :options="options"></v-server-table>
Vue Js
<script>
var config = {
"PMI-API-KEY": "erpepsimprpimaiy"
};
export default {
name: "user-profile",
data() {
return {
columns: ["golongan_name"],
options: {
requestFunction: function(data) {
return this.$http({
url: "api/v1/golongan_darah/get_all_data",
method: "post",
headers: config
}).then(res => {
this.data = res.data.data;
console.log(res);
});
},
filterable: ["golongan_name"],
sortable: ["golongan_name"],
filterByColumn: true,
perPage: 3,
pagination: { chunk: 10, dropdown: false },
responseAdapter: function(resp) {
return {
data: resp.data,
count: resp.total
};
}
}
};
}
};
</script>
This is the error:
enter image description here

How can I fix my Vue component to properly show my Vue-Chart.js line chart?

I would like to create a line chart using the vue-chartjs library.
What I have created so far produces no error but it also renders nothing but a blank canvas. When I switch to the developer view, I notice that all my data prints out. I'm just not sure why it's not rendering.
Here's my HTML and a snippet of the Vue code:
<div class="app">
<h1>Line Chart</h1>
<line-chart></line-chart>
</div>
<script>
Vue.component('line-chart', {
extends: VueChartJs.Line,
mounted () {
this.renderChart({
labels: this.chartDate,
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: this.expectedFund
}
]
}, {responsive: true, maintainAspectRatio: false})
}
})
new Vue({
el: '.app',
data: {
message: 'Hello World',
dataSetData: [],
expectedFund: '',
chartDate: '',
crossOver: '',
billing: ''
},
methods: {
getDataSet: function(dataField) {
console.log("get data sets");
console.log(this.dataSetData);
this.expectedFund = this.dataSetData.map(function(chartData) {
//alert("expected");
console.log(chartData);
return chartData.ExpectedFund;
});
this.billing = this.dataSetData.map(function(chartData) {
return chartData.Billing;
});
this.billing = this.dataSetData.map(function(chartData) {
return chartData.Billing;
});
this.chartDate = this.dataSetData.map(function(chartData) {
return chartData.date;
});
this.crossOver = this.dataSetData.map(function(chartData) {
return chartData.crossOver;
});
},
getListData: async function() {
const { data } = await axios.get(
"https://my-json-server.typicode.com/isogunro/jsondb/chartData"
);
return data;
}
},
mounted: async function() {
this.dataSetData = await this.getListData();
console.log("ok", this.dataSetData);
this.getDataSet();
}
})
</script>
If the pasted code is not enough, here's the Pen
After much struggle and bouncing around a bunch of Vue discords, I was able to figure out how to create a multi-line and bar-chart using Vue-Chartjs. It was a struggle worth it because I finally understand the use of props and how they work, which is what I was missing with the vuejs charts. Here's a pen showing the solution.
I am posting the json below because my charts use that data found in "my fake json server/typicode". It might change in the future, so I'm pasting it here.
{"chartData":
[
{
"date":"4/4/2019",
"totalCount":381,
"ExpectedFund":191,
"Funded":290,
"Billing":125,
"crossOver":241,
"AcceptedTotal":515
},
{
"date":"4/11/2019",
"totalCount":233,
"ExpectedFund":12,
"Funded":220,
"Billing":125,
"crossOver":211,
"AcceptedTotal":315
},
{
"date":"4/18/2019",
"totalCount":542,
"ExpectedFund":34,
"Funded":240,
"Billing":125,
"crossOver":125,
"AcceptedTotal":415
},
{
"date":"4/25/2019",
"totalCount":154,
"ExpectedFund":49,
"Funded":210,
"Billing":243,
"crossOver":35,
"AcceptedTotal":115
},
{
"date":"5/2/2019",
"totalCount":300,
"ExpectedFund":55,
"Funded":200,
"Billing":125,
"crossOver":145,
"AcceptedTotal":105
},
{
"date":"5/9/2019",
"totalCount":231,
"ExpectedFund":55,
"Funded":250,
"Billing":125,
"crossOver":355,
"AcceptedTotal":215
},
{
"date":"5/16/2019",
"totalCount":331,
"ExpectedFund":77,
"Funded":270,
"Billing":312,
"crossOver":15,
"AcceptedTotal":615
},
{
"date":"5/23/2019",
"totalCount":498,
"ExpectedFund":232,
"Funded":270,
"Billing":312,
"crossOver":15,
"AcceptedTotal":615
},
{
"date":"5/30/2019",
"totalCount":102,
"ExpectedFund":33,
"Funded":150,
"Billing":25,
"crossOver":155,
"AcceptedTotal":315
},
{
"date":"6/6/2019",
"totalCount":293,
"ExpectedFund":235,
"Funded":170,
"Billing":112,
"crossOver":125,
"AcceptedTotal":315
},
{
"date":"6/13/2019",
"totalCount":198,
"ExpectedFund":432,
"Funded":470,
"Billing":112,
"crossOver":315,
"AcceptedTotal":215
}
]
}

Vue2 update parent scope from modal component

I have a modal component that takes some input, creates a record on the backend and then as part of the success response I would like to push data to an object on the parent scope.
I have tried emitting an event from the child on success with the data I would like to append but I can't seem to get it to fire.
When addNote() successfully completes what would be the best approach to update the "notes" array object on the parent scope with the data I get back in my component?
Vue.component('modal', {
template: '#modal-template',
data: function() {
return {correctiveAction: this.correctiveAction}
},
props: ['notes'],
methods: {
addNote: function () {
axios.get('/quality/ajax/add-note/', {
params: {
action: this.correctiveAction
}
}).then(function (response) {
// append new corrective action
app = this;
this.$emit('addingNote', response.data.data.success[0].data);
//app.notes.push(response.data.data.success[0].data);
swal({
title: "Boom!",
type: "success",
text: "Corrective Action Successfully Added",
});
}).catch()
}
}
});
var app = new Vue({
el: '#app',
data: {
segment: "",
customer: "",
product: "",
startDate: "",
endDate: "",
notes: "",
showModal: false,
correctiveAction: ""
},
delimiters: ["<%","%>"],
methods: {
refresh: function () {
location.reload();
},
getNotes: function () {
app = this
axios.get('/quality/ajax/get-notes/').then(function (response) {
// populate notes
app.notes = response.data.data.success[0].notes
}).catch()
},
removeNote: function (id, index) {
app = this
axios.get('/quality/ajax/remove-note/', {
params: {
id: id
}
}).then(function () {
// remove note from list
app.notes.splice(index, 1);
swal({
title: "",
type: "success",
text: "Corrective Action Successfully Removed",
});
}).catch(function (err) {
console.log(err)
swal({
title: "",
type: "warning",
text: "Error Deleting Corrective Action",
});
return;
});
},
generateReport: function () {
$('#loading').show();
}).catch()
}
}
});
// get all active corrective actions
app.getNotes();
Well for one, you are setting a global variable app as a result of new Vue() and then you are blowing that variable away in your addNote method by setting app = this. That changes the variable to a completely different thing.
Also, you don't show anything listening to the addingNote event.
Don't use app everywhere. Use a scoped variable.
getNotes: function () {
const self = this
axios.get('/quality/ajax/get-notes/').then(function (response) {
// populate notes
self.notes = response.data.data.success[0].notes
}).catch()
},
And change addNote.
addNote: function () {
const self = this
axios.get('/quality/ajax/add-note/', {
params: { action: this.correctiveAction}
}).then(function (response) {
// append new corrective action
self.$emit('addingNote', response.data.data.success[0].data);
swal({
title: "Boom!",
type: "success",
text: "Corrective Action Successfully Added",
});
}).catch()
}
Looks like you should also fix removeNote.