Implement a formatter function to manipulate the JSON data retrieved from a REST API within the BootstrapVue framework

My bootstrap-vue vue.js v2.6 app is receiving JSON data from a REST API. The data structure looks like this:

{
    "fields": [
        {
            "key": "name",
            "label": "name",
            "sortable": true
        },  
        {
            "key": "item1",
            "label": "item1",
            "sortable": true
        },
        {
            "key": "item2",
            "label": "item2",
            "sortable": true            
        },
        {
            "key": "item3",
            "label": "item3",
            "sortable": true
        }
    ],
    "items": [
        {
            "name": "Field name 1",
            "item1": -0.05,
            "item2": -0.06,
            "item3": -0.07
        },
        {
            "name": " Field name 2 "
            "item1": -0.01,
            "item2": -0.02,
            "item3": -0.03
        },
        {
            "name": "Field name 3",
            "item1": -0.05,
            "item2": -0.06,
            "item3": -0.07
        }
    ]
}

I want to add a formatter function to display the items in percentage format, specifically for item2.

{
    "fields": [
        {
            "key": "name",
            "label": "name",
            "sortable": true
        },  
        {
            "key": "item1",
            "label": "item1",
            "sortable": true
        },
        {
            "key": "item2",
            "label": "item2",
            "sortable": true,
            "formatter": "value => { return (value + '%')}"
        },
        {
            "key": "item3",
            "label": "item3",
            "sortable": true
        }
    ],
    "items": [
         // Data remains the same
    ]
}

The Vue.js code I wrote for this purpose does not seem to work as expected. It's supposed to display item2 with a percentage sign added at the end but it doesn't. Any insight on what might be wrong would be appreciated.

I am using vue.js v2.6 and BootstrapVue.

Answer №1

Ensure that the formatter field is the actual name of a function when provided as a string, not the string value of the function itself.

If you encounter this issue, simply remove the quotes from the formatter value like so:

// "formatter": "value => { return (value + '%')}" ❌ don't use a string
"formatter": value => { return (value + '%')} ✅

Check out the demo here

Answer №2

To achieve adding a percentage sign as a suffix to the item2 column in a BootstrapVue table, there is an alternative method available.

Define the fields within your JavaScript code and only read data from the REST API json for the items.

It is uncommon for an API to dictate how the table fields should be structured. This information should be incorporated into your own code rather than relying on the API to define it. Extracting this information directly from the API goes against proper architectural design.

Below is an example of how the updated code will appear:

<template>
  <div class="container">
    <h1 class="pt-2 pb-3">Bootstrap Table</h1>
    <b-table striped hover :items="items" :fields="fields" primary-key></b-table>
  </div>
</template>

<script>

async function axiosGetRequest(url) {
  const axios = require("axios");  
  let res = await axios.get(url);

  return res.data;
}

export default {  
  data: data_init,
  mounted: function() {
      let url = "http://localhost:8080/temp.json";   
      
      axiosGetRequest(url).then((res) => {
        //this.fields = amend_fields(res.fields); //Don't read fields data from REST API. Define yourself.
        this.items = res.items;
        console.log(this.fields);
      });        
  },
};

function data_init() {  
  
  let init_data = {};
  init_data.fields = [
        {
            "key": "name",
            "label": "name",
            "sortable": true
        },  
        {
            "key": "item1",
            "label": "item1",
            "sortable": true
        },
        {
            "key": "item2",
            "label": "item2",
            "sortable": true,
            "formatter": "value => { return (value + '%')}"
        },
        {
            "key": "item3",
            "label": "item3",
            "sortable": true
        }
    ];
  init_data.items = {};

  return init_data;
}

</script>

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

Ways to personalize the onSubmit function within tinacms

Having an issue with my Tina project. I am trying to develop my own submit button in Tinacms project, rather than using the sidebar or top bar provided by tinacms. I want to customize a button for onSubmit functionality. Any suggestions on how to achieve ...

Empty form field when submitting form using ajax in C# MVC

I am encountering an issue while attempting to store form data in a database using $.ajax. The problem lies in the fact that upon submitting the form, the username is being saved as null, whereas the email and password are correctly stored. function Sav ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

Preventing Javascript array elements from being overwritten: Best practices

My challenge lies with the addToClients() function, which is designed to add a new value to the clients array whenever a button is pressed. The issue I am facing is that each time I press submit, the previous element in the array gets replaced by the new o ...

AngularJs tip: Harness the power of parallel and sequential function calls that have interdependencies

service (function () { 'use strict'; angular .module('app.user') .factory('myService', Service); Service.$inject = ['$http', 'API_ENDPOINT', '$q']; /* @ngInject ...

The switch statement remains unchanged for varying variables

Here is some code that I am working with: updateTable(selectedIndex) { console.log("running updateTable function"); let level = ''; // if (selectedIndex == 1){ // this.setState({level: 'day'}) // th ...

Discovering the quantity of arguments passed into a constructor in Node.js

In my Node.js code, I have a constructor that looks like this: function Tree() { //Redirect to other functions depending on the number of arguments passed. } I then created instances of objects like so: var theTree = new Tree('Redwood'); var ...

Creating diverse content for various tabs using JavaScript

I have developed a code that uses a for loop to generate tabs based on user input. var tabs = ""; var y = 1; for (var x = 0; x < tabNum; x++) { tabs += "<li class = 'tabbers'>" + "<a href='#tab'>Tab</a>" + "& ...

What could be causing my form not to Submit when attempting submission without utilizing the submit button?

Here is the code for my validation: $(function () { function validateForm() { // Code to validate form inputs } $('#myform').submit(validateForm); }); After this, I want to submit the form when a certain action occurs: < ...

Access the session on both routers

I currently have 2 different routers set up in my application: Router 1 app.post('/consultations', function(req, res) { req.session.name = 'administrator'; console.log('test', req.session.name); // the session is pro ...

Asking for something with no discernible purpose

I'm currently working on implementing a button that will trigger a request to display a login page. My goal is to restrict access to the login page only to project admins. To achieve this, I have their IP addresses and cross-reference them with those ...

Tips for interacting with Vue js buttons on JSP pages with Selenium WebDriver in Java

Having trouble locating elements rendered by vue.js within a JSP page. While I can find elements using xpath in normal JSP pages, those rendered by Vue.js remain elusive. For example, my JSP page includes: <div id="fileUploadDiv" style="display: flex; ...

How can I create a rectangular border around text using the HTML5 canvas?

How can I dynamically draw fitted rectangles around text labels (person's full name) without fixed sizes, taking into account that the labels vary in lengths? Below is the code used to draw the text labels: var ctx = document.getElementById('ma ...

Sending Component Properties to Objects in Vue using TypeScript

Trying to assign props value as an index in a Vue component object, here is my code snippet: export default defineComponent({ props:{ pollId:{type: String} }, data(){ return{ poll: polls[this.pollId] } } }) Encountering errors wh ...

Using jQuery to select the next table cell vertically

Is there a way to utilize jQuery to access the cell (td) directly below a given cell in a traditional grid-layout HTML table (where each cell spans only one row and column)? I understand that the code below will assign nextCell to the cell immediately to ...

I'm new to learning JavaScript and I'm wondering how I can receive a single alert using only the if operator

Extracted from the book "Beginning JS 4th edition", this code snippet displays two alert messages when loaded in a browser due to two NaN entries in an array. To ensure that only one alert is shown every time, how can I achieve this using the if operator? ...

Is it possible to navigate to the Next page using a different button instead of the pagination controls

Is it possible to navigate to the next page upon clicking a button labeled "Press me"? Here is the code snippet: <!doctype html> <html ng-app="plunker"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/an ...

Issue: Upon attempting to connect to a vsftpd server deployed on AWS using the npm module ssh2-sftp-client, all designated authentication methods have failed

Code snippet for connecting to the vsftpd server sftp.connect({ host: "3.6.75.65" port: "22" username: "ashish-ftp" password: "*******" }) .then(() => { console.log("result") }) .catch((err)=>{ ...

Dealing with Form Submission on Enter Keypress in VueJs

Transitioning from Angular to Vue was smooth until I encountered a frustrating issue that seems to have been ignored by VueJS developers. The challenge of allowing users to submit a form by pressing enter from an input field had me pulling my hair out. How ...

Retrieving specific data from nested arrays in Vue.js

I am currently working on Vue.js template development and facing an issue with filtering nested data in a faq section. When I try to add a search bar, the nested data array returns all data without proper filtering. Dom <v-container> <v ...