如何在 Vue 中的数组中存储格式化数据,watch 和 v-model 不保存格式化数据?

How to store formatted data in Array in Vue, watch and v-model aren't saving formatted data?

我有多个文本框,当用户在不同的文本框中键入内容时,我想要一个数组来存储所有这些格式化数据。

格式化后的数据在m:ss(m-分,s-秒)

现在,所有不同的文本框显示相同的值,因为只有一个 this.formatTime。

我们如何更改它以便 v-model 遍历数组,并将其添加到格式化值数组中?

文本框应显示格式化值并将其存储在 allFormatValues[] 中。

我真的卡在这上面了,谢谢你的时间!

<div id="app">
   <div
      v-for="(input, index) in valueInputs"
      :key="index"
    >
     <input
         v-model="formatTime" //want to use allFormatValues[index], instead
         id="time-input"      //but this loses the formatting if I change to 
                              //above
         type="text"
     />
  </div>
</div>

 watch: {
   formatTime () {
      const totalLength = this.formatTime.length;
      let a = this.formatTime.replace(/[^0-9]/g, "")
        .substr(0, 1);

      const b = this.formatTime.replace(/[^0-5]/g, "")
        .substr(1, 1);

      const c = this.formatTime.replace(/[^0-9]/g, "")
        .substr(2, 1);
      if (totalLength >= 2) {
        a = `${a.substring(0, 1)}:${b}${c}`;
      }
      this.formatTime = a;
    },
}

我有一个数组,我想遍历并设置这个值

data () {
  return {
  valueInputs: [],    // a list of inputs
  allFormatValues: [] // want to store all the formatted values here by the index
 }
}

更好的解决方案是使用计算属性。

首先,让你的输入改变原来的值。

<input v-model="input"
       id="time-input" 
       type="text"/>

然后,为了更简洁的代码,制作 formatValue 方法

methods: {
    formatValue(value) {
        const totalLength = value.length
        let a = value.replace(/[^0-9]/g, "")
            .substr(0, 1)

        const b = value.replace(/[^0-5]/g, "")
            .substr(1, 1)

        const c = value.replace(/[^0-9]/g, "")
            .substr(2, 1)
        if (totalLength >= 2) {
            a = `${a.substring(0, 1)}:${b}${c}`
        }

        return a
    },
}

最后创建计算 属性

computed: {
    formattedValues() {
        return this.valueInputs.map(value => this.formatValue(value))
    }
}

您可以将 <input> 的值绑定到迭代器,并添加一个 input 事件处理程序调用 formatTime() 来更新 valueInputs:

  1. 绑定<input>.valueinput变量:

    <input :value="input" ...>
    
  2. <input> 上,添加一个 input 事件处理程序,用于接收迭代器索引和事件值:

    <input @input="formatTime(index, $event.target.value)" ...>
    
  3. 更新 formatTime() 方法以接收 index$event.target.value 参数。还可以使用 vm.$set() 以新值响应式更新 valueInputs[index]

    export default {
      methods: {
        formatTime(index, input) {
          const totalLength = input.length;
          let a = input.replace(/[^0-9]/g, "").substr(0, 1);
    
          //...
    
          this.$set(this.valueInputs, index, a)
        }
      }
    }
    

demo