1
votes

Im trying to build an input field with bootstrap-vue, in which the user can input any desired number and it should be formatted to a decimal number with 3 places.

This is what I've got so far. The focusOut-Method alerts my desired value, but I have no idea how to update the value in the table row with it, as it is called by value. Do you have any idea?

<template>
  <div>
    <b-table :items="items" :fields="fields" >
      <template v-slot:cell(price)="row">
          <b-form-input 
            v-model="row.item.price"
            @blur="focusOut($event, row.item.price)"
          />
      </template>
    </b-table>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      fields: [...],
    };
  },
  computed: {
    items: function () {
      return [{price: 3.9}, {price: 5}, {price: 9.333}];
    },
  },
  methods: {
    focusOut: function (event, value) {
      if (["Arrow", "Backspace", "Shift"].includes(event.key)) {
        this.preventNextIteration = true;
        return;
      }
      if (this.preventNextIteration) {
        this.preventNextIteration = false;
        return;
      }

      value = parseFloat(value.replace(",", ".")).toLocaleString(undefined, {
        minimumFractionDigits: 3,
      });
      alert(value);
    },
  } ....
};
</script>
1

1 Answers

1
votes

First, items should be a simple data property not a computed one (because you're not doing any calculations), second, Try to get the row index and the cell name (in this case is price) then inside the method update the cell at the given row index :

   <template v-slot:cell(price)="row">
          <b-form-input 
            v-model="row.item.price"
            @blur="focusOut($event, row.item.price,'price',row.index)"
          />
      </template>
data: function () {
    return {
      fields: [...],
      items:  [{price: 3.9}, {price: 5}, {price: 9.333}]
    };
  },

  methods: {
    focusOut: function (event, value,field,index) {
    ... 
  let _value = parseFloat(value.replace(",", ".")).toLocaleString(undefined, {
        minimumFractionDigits: 3,
      });
 //update the field at the given index
  this.$set(this.items,
              index,
                {...this.items[index],[field]:_value})//field represents price

LIVE DEMO