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

What is the best way to keep a text editable in a razor editor without it vanishing?

I'm on a quest to find the name for a certain functionality that has been eluding me, and it's truly driving me up the wall. Check out the razor code snippet I've been using to exhibit my form inputs: <div class="col-sm"> ...

Guide on sending two dynamically generated select box values through ajax in order to retrieve values for a third select box

I am currently working on a task where I need to populate the 3rd select box based on the selections made in the first two select boxes, which have dynamic values. Below is the jQuery ajax code snippet that I have written (Please note that this code curre ...

The expiry date of the cookie remains unchanged

When attempting to create a cookie and specify an expiration date, I am encountering an issue where it remains as "Session". This problem is occurring in Google Chrome. I'm looking for insights on what might be causing this behavior. The code snippe ...

Is there a similar alternative to {useLocation} provided by 'react-router-dom' that can be used in Next.js?

import { useLocation } from 'react-router-dom'; Currently utilizing Nextjs, I'm seeking assistance in finding an alternative for useLocation ` import Link from 'next/link'; import { FC } from 'react'; import {useRout ...

What strategies can be employed to maintain reliable datetime management for a reservation system operating in diverse time zones?

Looking at the big picture: An interesting scenario arises when a hotel owner specifies a time frame for booking reservations at a restaurant (5pm - 10pm). Along with this information, there is also a timezone provided to ensure that dates are displayed i ...

Customize the Add to Cart notifications for a specific product category with Shortcode in WooCommerce

I am attempting to customize the Add to Cart messages based on product categories for the "add_to_cart" shortcode. I have successfully altered the message on individual product pages and archive pages using the code below. However, the shortcode used in p ...

When working with Nuxt.js and i18n, I prefer using the t method for the href of an a tag and a custom data attribute instead of nuxt-link

Creating dynamic multilingual websites from the backend to the replacement of large websites has been a smooth process. Now, I am stepping into the frontend realm for the first time using Nuxt.js + i18n. <a href="https://gooogle/en.com" data-link="fuga ...

"Troubleshooting: Angular ng-show not triggering correctly upon first loading of the

Utilizing Angular's ng-show directive to adjust the display of questions in a quiz and show a result upon completion, everything is functioning as intended except for the initial question. Upon loading the quiz, $scope.image is initialized as false. S ...

What steps do I need to take to integrate FontAwesome with the vue-cli webpack-simple template?

First, I create a new project using vue-cli: vue init webpack-simple grid-prototype Next, I add FontAwesome to my project via npm: npm install --save fontawesome Once installed, I include it in my main.js file with the following code: import 'fon ...

Showing information retrieved from an API and rendering it on an HTML page

My aim is to showcase a list of calculated results fetched from a local server. In the console, this data appears as an array of objects, but on the webpage, it is being displayed as separate string characters for each li element. How can I display the con ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

ERROR: The value property is undefined and cannot be read in a ReactJS component

Can someone help me with the error I'm encountering in the handleChange function? I'm not sure what the issue could be. const [testState, setTestState] = useState({ activeStep:0, firstName: '', lastName: '&apos ...

Ways to remove a JSON item based on its index position?

In my JSON object, I am trying to find a way to remove the first element. Here is an example of what I have: var obj1 = {property:'something', does:'somethingElse', is:'somethingCool'}; var obj2 = {does:'somethingElse&ap ...

Best practices for handling APIs in Vue

After spending hours reading documentation and searching online for the best way to manage API calls in larger projects, I have yet to find a solution that meets my needs. My goal is to create a service or facade for the backend that can be easily integra ...

Directives causing disruption to one another

Two directives are at the same level in my code: function signUpForm(djangoAuth, Validate){ return{ restrict:'A', controller:["$rootScope","$scope",function($rootScope, $scope){ $scope.submitFunction = function(formData){ ...

The ng-view DIV in Angular JS 1.x mysteriously vanishes

Currently, I am working on a project that involves angularJS and ASP.NET in Visual Studio 2013. However, I have encountered a frustrating issue where my DIV node for ng-view is being replaced with an ng-view comment without any errors appearing while testi ...

I am looking to incorporate a dropdown feature using Javascript into the web page of my Django project

According to the data type of the selected column in the first dropdown, the values displayed in the columns of the second dropdown should match those listed in the JavaScript dictionary below, please note: {{col.1}} provides details on the SQL column data ...

Error message encountered: When attempting to execute 'postMessage' on a 'Worker', the operation failed as the object of type 'Array' could not be cloned

We are currently in the process of transitioning our code base from Vue 2 to Vue 3. Most things are working smoothly with HERE maps, except for one hiccup involving the .addObject() event. Unfortunately, this event keeps failing and displays the error mess ...

hover effect with fading transition while mouse is still hovering

Is there a way to create a fade-in/fade-out effect on a div without the mouse needing to leave the area? Let me provide a clearer explanation: When the mouse enters the object The object gradually fades in Then, after a delay, the object fades out while ...

Utilize the #value template in PrimeVue Dropdown to retrieve country code for setting the default selected flag

In the student edit modal, I have a Dropdown where I need to display a flag for the default country. When using PrimeVue, I can access the country code from a template using #option="slotProps", but not with #value="slotProps". This m ...