Vue中如何在数组存储格式化数据,v-model与watch无法保存格式化值?
解决方案
核心思路
- 放弃绑定单个公共变量,将v-model拆为
value绑定+input事件监听的写法,针对每个输入框的索引单独处理格式化逻辑 - 输入内容变化时,将当前输入框的内容格式化后直接更新到
allFormatValues数组的对应索引位置,同时保证响应式更新
代码修改
1. 模板部分调整
替换原input的绑定逻辑,同时修正重复id的问题:
<div id="app"> <div v-for="(input, index) in valueInputs" :key="index" > <input :value="allFormatValues[index]" @input="handleTimeInput($event, index)" :id="`time-input-${index}`" type="text" /> </div> </div>
2. 逻辑部分调整
移除原formatTime变量和对应的watch监听,新增输入处理方法,同时注意新增输入框时要同步初始化allFormatValues的对应项:
<script> export default { data () { return { valueInputs: [], // 输入框列表 allFormatValues: [] // 按索引存储所有格式化后的值 } }, methods: { handleTimeInput(e, index) { const inputVal = e.target.value const totalLength = inputVal.length let a = inputVal.replace(/[^0-9]/g, "") .substr(0, 1); const b = inputVal.replace(/[^0-5]/g, "") .substr(1, 1); const c = inputVal.replace(/[^0-9]/g, "") .substr(2, 1); if (totalLength >= 2) { a = `${a.substring(0, 1)}:${b}${c}`; } // Vue2使用$set保证数组响应式更新,Vue3可直接写 this.allFormatValues[index] = a this.$set(this.allFormatValues, index, a) }, // 示例:新增输入框的方法,需同步初始化allFormatValues对应项 addInput() { this.valueInputs.push({}) this.allFormatValues.push('') } } } </script>
注意事项
如果是动态新增输入框,必须在给valueInputs添加项的同时,给allFormatValues也push一个空字符串作为初始值,避免绑定时出现undefined的问题。
内容的提问来源于stack exchange,提问作者Suzy
相关产品推荐
相关产品推荐

