首页 > 解决方案 > v-for 的索引作为 v-model 的值

问题描述

我需要将 v-for 的索引设置为动态 v-model,但我不知道如何在不触发错误的情况下做到这一点,我已经尝试过这个工作但并不优雅,并且在控制台中给了我错误:

在我的模板部分:

<div v-for="(ob, index) in $v.especifications.$each.$iter" :key="index" class="row">
    <div class="form-group" :class="{ 'form-group--error': $v.$error }">
        <label for="number">Número:</label>
        <input v-model="ob.numero.$model = parseInt(index)+1" type="number" class="form-control" id="number" aria-describedby="number" disabled>
        <div class="alert alert-danger" role="alert" v-if="ob.numero.$dirty && !ob.numero.required">Es requerida una fecha de inicio</div>
    </div>
</div>

在我的脚本部分:

export default {
    data () {
      return {
        especifications: [{
          descripcion: '',
          numero: '',
          cantidad: ''
        }],
      }
    }
  }

错误:

Module Warning (from ./node_modules/eslint-loader/index.js):
error: 'v-model' directives require the attribute value which is valid as LHS (vue/valid-v-model)

error: 'v-model' directives cannot update the iteration variable 'x' itself (vue/valid-v-model)

标签: javascriptvue.jsvue-cliv-forv-model

解决方案


使用:value=ob.numero.$model而不是v-model

然后添加一个@change处理程序:

@change="updateNumero(index, $model)"

然后创建该函数:

methods: {
  updateNumero(index, model) {
    $v.especifications.$each.$iter[index].numero[model] = parseInt(index) +1
  }
}

我不能保证这是被动的,但它会起作用。


推荐阅读