I've created a custom Vue.js component that retrieves orders from a Woocommerce store. These orders include product variations and are received in object form.
Before displaying the data in a table, I need to format the object accordingly.
This is a snippet of my code:
<template>
<div>
<vue-good-table
title=""
:columns="columns"
:rows="variationOrders"
:paginate="true"
:lineNumbers="true"/>
</div>
</template>
<script>
export default {
data: function() {
return {
variationOrders: [],
columns: [
{
label: 'Order#',
field: 'order_id',
filterable: true,
},
// Other column configurations...
],
}
},
methods: {
getTotals: function() {
var self = this;
var productId = document.getElementById('product-id').getAttribute('data-id');
axios.get('/api/v1/order_variations/' + productId)
.then(function (response) {
self.variationOrders = response.data.order_variations;
//console.log(response.data);
})
.catch(function(error) {
//
});
},
formatVariations: function(variationOrders) {
console.log(variationOrders);
},
},
mounted: function() {
this.getTotals();
setInterval(() => {
this.getTotals();
}, 5000);
}
}
</script>
In the Variations column, I attempt to pass a formatting function, but encounter issues passing the API response object.
The error messages I receive are as follows:
If I use
, I getthis.formatVariations(this.variationOrders)
undefined
.If I use
, I getthis.formatVariations(variationOrders)
.[Vue warn]: Error in data(): "ReferenceError: variationOrders is not defined"
I suspect that at the time the function is called, the variable doesn't exist yet.
Is there something I'm overlooking here?
UPDATE 1
I made some adjustments to the code, getting closer to a solution, but unfortunately, the view doesn't update as expected.
Here's what I modified:
<template>
<div>
<vue-good-table
title=""
:columns="formattedColumns"
:rows="variationOrders"
:paginate="true"
:lineNumbers="true"/>
</div>
</template>
<script>
export default {
data: function() {
return {
variationOrders: [],
columns: [
// Column configurations...
],
}
},
methods: {
// Methods definition...
},
computed: {
formattedColumns(){
const formattedVariations = this.formatVariations(this.variationOrders);
console.log(formattedVariations);
return this.columns.map(c => {
if (c.label == "Variations") {
return {label: "Variations", field: formattedVariations , html: true}
}
return c;
})
}
},
mounted: function() {
this.getTotals();
setInterval(() => {
this.getTotals();
}, 5000);
},
}
</script>
Update 2
An example of the output from the formatVariations() function is shown below:
// Example output goes here.
Update 3
A single item from the array returned by the API looks like this:
// Sample API response snippet displayed here.