Prepare the column data for Vue Good-Table by formatting it beforehand

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:

  1. If I use

    this.formatVariations(this.variationOrders)
    , I get undefined.

  2. If I use

    this.formatVariations(variationOrders)
    , I get
    [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.

Answer №1

self.variationOrders is not defined in the data method; self is only accessible within the scope of the getTotals method.

Instead of that, utilize a computed property to structure columns.

computed:{
  formattedColumns(){
    const formattedVariations = this.formatVariations(this.variationOrders)
    return this.columns.map(c => {
      if (c.label === "Variations")
        return {label: "Variations", field: formattedVariations , html: true}

      return c
    })
  }
}

Ensure to use the computed property in the template.

<vue-good-table
  title=""
  :columns="formattedColumns"
  :rows="variationOrders"
  :paginate="true"
  :lineNumbers="true"/>

The computed property needs to be updated whenever there is a change in variationOrders.

Edit

The previous solution answered the question but did not generate the desired table output (as per my understanding). This misconception arises from a misinterpretation of how vue-good-table operates.

To achieve the desired result, you need to incorporate HTML formatting for cell content using the scoped slot table-row. Here is an example of how the template should be structured:

<vue-good-table
  title=""
  :columns="columns"
  :rows="variationOrders"
  :paginate="true"
  :lineNumbers="true">
  <template slot="table-row" scope="props">
    <td>{{ props.row.order_id }}</td>
    <td>{{ props.row.customer_name }}</td>
    <td><span v-html="formatVariations(props.row.variation)"></span></td>
  </template>
</vue-good-table>

An update has been made to the formatVariations method as well:

formatVariations: function(variationOrders) {
  let parsed = JSON.parse(variationOrders).map(order => {
    return `${order.key} : ${order.value} <br>`
  })
  return parsed.join('');
},

This assumes that the data format follows this structure:

[
  {
    order_id: 1,
    customer_name: "Bob NewHart",
    qty: 10,
    product_name: "Hats",
    variation: '[{"id": 35, "key": "choose-your-cake", "value": "Naked"}, {"id": 36, "key": "choose-sugar", "value": "Yes"}]'
  },
  {
    order_id: 2,
    customer_name: "Mary Lamb",
    qty: 10,
    product_name: "Necklaces",
    variation: '[{"id": 35, "key": "choose-your-cake", "value": "Naked"}, {"id": 36, "key": "choose-sugar", "value": "Yes"}]'
  },
]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am experiencing continuous redirection back to the original website on my WordPress platform

Hello everyone, hope you're all doing well! Here's my current situation: 1- I have a production WordPress website running on a virtual machine, 2- I made a clone of the virtual machine and changed its IP address and DNS name, 3- I updated the wp- ...

Is the validation for the 'prop' property missing in props?

Seeking assistance with react's forwardRef feature. Currently encountering errors related to missing props validation in FadeContents. Is there a way to resolve this issue? It seems like the props need to be defined somewhere in order to be used withi ...

Is there a way to dynamically change the helperText of a Material UI TextField using its current value through code?

I'm currently attempting to dynamically change the helperText of a Material UI TextField based on the value entered into the field. Below is my current implementation: const defaultScores = { STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CH ...

PubNub's integration of WebRTC technology allows for seamless video streaming capabilities

I've been exploring the WebRTC sdk by PubNub and so far, everything has been smooth sailing. However, I'm facing a challenge when it comes to displaying video from a client on my screen. Following their documentation and tutorials, I have writte ...

The optimal method for storing tokens in Vue when using Laravel Sanctum

I am currently working on an application built with Laravel and Vue.js. My current focus is implementing the login/logout functionality using Laravel Sanctum. Here is my scenario: I already have the backend methods for login/logout/register set up, but I ...

Navigating through drop-down menus using jQuery

I need help with a JavaScript script that can calculate the total number of points based on selected checkboxes and dropdown values. Currently, my script is able to iterate through checkboxes and assign 1 or 2 points based on their classes, but I'm st ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

Incorporate image into Vue.js form along with other information

I have been successfully sending the content of multiple fields in a form to the Database. Now I am looking to add an additional field for uploading images/files and including it with the other form fields, but I am unsure about how to accomplish this task ...

Are there any compatibility issues with uuid v1 and web browsers?

After researching, I discovered that uuid version1 is created using a combination of timestamp and MAC address. Will there be any issues with browser compatibility? For instance, certain browsers may not have access to the MAC address. In my current javaS ...

What is the best way to incorporate "thread.sleep" in an Angular 7 app within a non-async method like ngOnInit()?

Despite the numerous questions and solutions available on Stack Overflow, none of them seem to work when called from a component's init function that is not asynchronous. Here's an example: private delay(ms: number) { return new Promise( ...

Install Chakra UI in the latest Next.js project directory

Recently, I decided to incorporate Chakra UI v2.4.9 into my Next.js project running on version v13.1.6. To ensure a seamless integration, I followed the detailed instructions provided in Chakra UI's official guide for Next.js. However, I encountered s ...

Transforming into an input field from a dropdown with Bootstrap select when using AJAX in js.erb

I'm encountering a small issue while updating the view results via AJAX in Ruby on Rails (js.erb). Specifically, when I update/render the form using AJAX, the selectpicker transforms into a simple input and disappears from the view. Any suggestions on ...

Can the server URL be concealed within the dist folder in Vue.js?

Currently working on a Vue.js project that will need to be distributed once development is complete. But how can I ensure its security? The js files in the "dist" folder contain the server URL, such as http://sample.org:8001/. What if a user changed all t ...

Vuex - Avoid changing the vuex store state directly without using mutation handlers or getters

/pages/index.vue computed: { getFirstValue() { return this.$store.state.escapeOnline.slice(0, 1); } } /store/index.js export const state = () => ({ escapeOnline: [{id: 1, name: 'titi'}, {id: 2, 'toto'}], }) Whenever I attem ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...

Working with JSON structure using Javascript

I successfully transformed an XML file into a JSON format, but now I need to manipulate the data in order to achieve a specific desired structure. Here is the Original format { "machine": "Hassia2", "actual_product_date": "08/24/2017", "holdi ...

There was an issue encountered when trying to call a PHP file within an HTML table using Ajax and data.html

For a small project, I have various news items that need to be included from the "news_all.php" file into table data within the "dashboard.php" file. Due to the predefined root structure restrictions, using include('news.php') is not an option. I ...

How can I code a script to import JSON data into MongoDB database?

I have a JSON file named "data.json" that contains an array of people's names as shown below: "data": [ { { "name":"John", "age":30, } { "name":"Mark", "age":45, } } ] I am ...

Managing OAuth2 redirections on the frontend: Best practices

I am currently working on implementing an OAuth2 flow for a Single Page Webapp, but I am facing challenges in dealing with Frontend/JavaScript redirects. Regarding the backend setup, I have it all sorted out: utilizing a library that takes care of everyth ...

Ways to extract the value from a jQuery object

How can I retrieve the selected time value using a jQuery plugin and save it on a specific input element within the page? Refer to the plugin and code provided below: http://jsfiddle.net/weareoutman/YkvK9/ var input = $('#input-a'); input.cloc ...