由'v-model' directives cannot update the iteration variable itself 引出的一个问题及解决方案

13,843 阅读1分钟

由'v-model' directives cannot update the iteration variable itself 引出的一个问题及解决方案

看下面几个例子:

let arr = [1, 2, 3]
for(let value of arr) {
    value = 10
}
console.log(arr)//arr 并不会改变

这就好比:

let a = {
    age: 123
}
let b = a;

b = 123;
console.log(a)//a并没有改变

这就解释了vue中的这么一个情况:

const categorys = [1, 2, 3 ,4]
<div
  v-for="(item, index) in categorys"
  :key="index"
>
  <input v-model="item" />
</div>

解决方案:

const categorys = [1, 2, 3 ,4]
const categorysOther  = this.categorys
<div
  v-for="(item, index) in categorys"
  :key="index"
>
  <input v-model="categorysOther[index]" />
</div>

其他都是为了观察方便,重点就是用categorysOther替代item !