Vue + elementUI 表格输入框只允许输入固定位整数或固定位小数

前期思路:

使用 watch 进行侦听,当数据改变时做相应的处理。但是在表格中,行的数量可能是不确定的,且很难用 watch 去进行侦听某一个属性,所以放弃使用 watch。

解决办法:

1. 在 data 中用一个变量保存符合标准的旧值;

2. 在输入框的 input 事件处理函数中对值进行处理,若符合标准,则给 data 中的变量赋值,否则则将 data 中的变量的值赋给输入框;

3. 输入框失焦时清除 data 中保存的旧值。

代码:

<el-table>
    <el-table-column
        v-for="(it, index) in tableData"
        :key="index"
        :prop="it.key"
        :label="it.title"
    >
        <div slot-scope="scope">
            <template v-if="it.key === 'price'">
                <el-input 
                    type="number" 
                    v-model="scope.row[it.key]"
                    @keyup.native="changePrice($event)"                 
                    @blur="clearPrice" 
                    placeholder="请输入" 
                    style="width: 140px" 
                >
                    <template slot="append">元</template>
                </el-input>
            </template>
            <span v-else> {{scope.row[it.key]}} </span>
        </div>
    </el-table-column>
</el-table>
export default {
    data () {
        return {
            tableData: [
                {
                    name: "显示器",
                    price: ""
                },
                {
                    name: "主机",
                    price: ""
                }
            ],
            oldPrice: null
        }
    },

    methods: {        
        changePrice (event) {
            // 最多八位整数两位小数
            let reg = new RegExp("^[0-9]{1,8}([.][0-9]{1,2})?$");

            event.target.value = event.target.value.replace(/[^\d\.]/g,'');

            if (reg.test(event.target.value)){
                this.replaceValue = event.target.value;
            } else {
                if (event.target.value) {
                    // 避免删完数据总是剩余一位
                    event.target.value = this.replaceValue
                }
            }
        },

        clearPrice () {
            this.oldPrice = null;
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值