1

I have this code that uses the VueGoodTable component, and I need the user to be able to change the unit of the amount (a mone on the fly :

<template>
  <div class="container">
    <h1>This is the datatable page</h1>
    <div class="unit">
      <!-- Basic radio that will select the unit (v-model="unit") (options are 1, 1000 and 1000000), I confirmed that this works using vue-devtools and does indeed change the unit -->
    </div>
    <vue-good-table :columns="columns" :rows="rows" />
  </div>
</template>

<script>
import "vue-good-table/dist/vue-good-table.css";
import { VueGoodTable } from "vue-good-table";

export default {
  components: {
    VueGoodTable,
  },
  data() {
    return {
      // I need to access this unit at the formatFn function below
      unit: 1000,
      columns: [
        // Reference and title columns
        {
          label: "Amount",
          field: "amount",
          type: "number",
          formatFn: function (val) {
            let returnedVal = val / 100;
            // I need to access the unit here, "this" returns the wrong object : {label: "Amount", field: "amount"...}, so doing this.unit is wrong
            returnedVal = returnedVal / this.unit;
            return returnedVal.toFixed(2);
          },
        },
      ],
      rows: [],
    };
  },
  // methods to fetch the rows using a fake json-server api
};
</script>

enter image description here

As you can see, the value comes out as NaN. So how do I access the unit correctly ?

1 Answer 1

1

columns should be a computed property to react to the unit changes :

export default {
  components: {
    VueGoodTable,
  },
  data() {
    return {
      // I need to access this unit at the formatFn function below
      unit: 1000,
     
      rows: [],
    };
  },
computed:{
   columns(){
    return [
        
        {
          label: "Amount",
          field: "amount",
          type: "number",
          formatFn: (val) =>{
            let returnedVal = val / 100;
            returnedVal = returnedVal / this.unit;
            return returnedVal.toFixed(2);
          },
        },
      ]


 }
}
  // methods to fetch the rows using a fake json-server api
};
Sign up to request clarification or add additional context in comments.

3 Comments

I just tried this, didn't work for me as "this" still refers to "{label: "Amount", field: "amount", type: "number", typeDef: {…}, formatFn: ƒ}"...
Oh I didn't implement your solution fully, my bad. I kept using "function(val)" instead of "(val) =>", it works now, thank you.
You're welcome, it's my pleasure to see that works for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.