【问题标题】:b-form-input how to modify/format input with @blur in bootstrap-vue table cell?b-form-input 如何在 bootstrap-vue 表格单元格中使用@blur 修改/格式化输入?
【发布时间】:2020-11-12 12:10:55
【问题描述】:

我正在尝试使用 bootstrap-vue 构建一个输入字段,用户可以在其中输入任何所需的数字,并且应该将其格式化为 3 位的十进制数字。

这是我到目前为止所得到的。 focusOut-Method 会提醒我想要的值,但我不知道如何用它更新表行中的值,因为它是按值调用的。你有什么想法吗?

<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>

【问题讨论】:

    标签: vue.js vuejs2 bootstrap-vue


    【解决方案1】:

    首先,items 应该是一个简单的数据属性,而不是计算属性(因为您没有进行任何计算),其次,尝试获取行索引和单元格名称(在本例中为 price)然后在方法内部更新给定行索引处的单元格:

       <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

    【讨论】:

    • 谢谢,我试过了,它可以很好地更新我的 items-object 中的值。但新值未显示在 b-form-input 中。有没有办法更新它?
    • 您在最后一个答案编辑中尝试过吗?请查看codesandbox.io/s/modest-feather-ek82e?file=/App.vue
    • 你的例子做了我想要实现的,所以它一定是我遗漏的代码中的东西。我会试着弄清楚这一点。再次感谢您的努力!
    猜你喜欢
    • 2020-11-01
    • 2021-04-21
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2015-09-30
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多