Vue2 update parent scope from modal component - vue.js

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.

Related

Data not being passed from Child Data to Parent Props

I have a Request Form Component, and within this request form Component I have a Dropdown Menu Component, which I will link both below. All values in my table are pushed into an object upon hitting the Submit Button. However my dropdown selection is only being picked up by my console.log and not being pushed into the Object.
I'm not so familiar with Vue, so I'm not sure what direction to go in for fixing this. I'll attach the relevant (?) pieces of code below.
Parent Component:
<SelectComponent :selected="this.selected" #change="updateSelectedValue" />
export default {
fullScreen: true,
name: 'CcRequestForm',
mixins: [BaseForm],
name: "App",
components: {
SelectComponent,
},
data() {
return {
selected: "A",
};
},
props: {
modelName: {
default: 'CcRequest',
},
parentId: {
type: Number,
default: null,
},
},
mounted() {
this.formFields.requester.value = this.currentRequesterSlug;
},
destroyed() {
if (!this.modelId) return;
let request = this.currentCcRequest;
request.params = request.params.filter(p => p.id)
},
computed: {
...mapGetters(['ccTypesForRequests', 'currentRequesterSlug', 'currentCcRequest']),
ccTypesCollection() {
return this.ccTypesForRequests.map((x)=>[x.slug, this.t(`cc_types.${x.slug}`)]);
}
},
methods: {
addParam() {
this.addFormFields(['params'], {
slug: '',
name: '',
isRequired: true,
description: '',
typeSlug: '',
selected: ''
});
},
deleteParam(idx){
this.removeFormFields(['params', idx]);
},
restoreParam(idx){
this.restoreFormFields(['params', idx])
},
$newObject() {
return {
slug: '',
name: '',
isAbstract: false,
requester: '',
description: '',
status: 'inactive',
params: [],
selected: ''
};
},
$extraPrams() {
return {
parentId: this.parentId,
};
},
updateSelectedValue: function (newValue) {
this.selected = newValue;
},
},
watch: {
selected: function (val) {
console.log("value changed", val);
},
},
};
Child Component:
<script>
export default {
name: "SelectComponent",
props: {
selected: String,
},
computed: {
mutableItem: {
get: function () {
return this.selected;
},
set: function (newValue) {
this.$emit("change", newValue);
},
},
},
};
You have to define the emit property in the parent component, or else it won't know what to expect. That would look like:
<SelectComponent :selected="this.selected" #update-selected-value="updateSelectedValue" />
Check out this tutorial for more information: https://www.telerik.com/blogs/how-to-emit-data-in-vue-beyond-the-vuejs-documentation
To update selected property inside the object, in this constellation, you need to update object property manually upon receiving an event, inside of updateSelectedValue method. Other way could be creating a computed property, since it's reactive, wrapping "selected" property.
computed: {
selectedValue () {
return this.selected
}
}
And inside of object, use selectedValue instead of selected:
return {
...
selected: selectedValue
}

Uncaught ReferenceError: then is not defined in Element Ui Plus

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?

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