Abderrahim Benmelouka
Abderrahim Benmelouka

Reputation: 405

VueJS access data attribute from another attribute

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 ?

Upvotes: 1

Views: 899

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 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
};

Upvotes: 1

Related Questions