如何使这项工作:
<div v-for="index in 4">
<input v-model="'invoice_' + index" >
</div>
就像这样:
<div v-for="index in 4">
<input v-model="invoice_1" >
</div>
答案 0 :(得分:4)
如果将所有发票_ 的变量放在一个对象中,然后按键引用它们会更好,如下所示:
new Vue({
el: '#app',
data: {
invoices: {
invoice_1: '1',
invoice_2: '2',
invoice_3: '3',
invoice_4: '4'
}
}
})
<script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>
<div id="app">
<div v-for="index in 4">
<input v-model="invoices['invoice_' + index]">
</div>
</div>
答案 1 :(得分:2)
如果您无法更改数据的结构,you can access the data object via $data
。因此,您可以通过$data['invoice_' + index]
:
new Vue({
el: '#app',
data() {
return {
invoice_1: 'a',
invoice_2: 'b',
invoice_3: 'c',
invoice_4: 'd'
}
}
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<div v-for="index in 4">
<input v-model="$data['invoice_' + index]" >
</div>
</div>
&#13;
但是,我同意Psidom的意见,如果你能够改变你的数据结构会更有意义。虽然,我会使invoices
成为一个数组,只需通过索引访问每个发票。这样您就不需要使用索引明确命名每张发票:
new Vue({
el: '#app',
data() {
return {
invoices: ['a', 'b', 'c', 'd' ]
}
}
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<div v-for="index in 4">
<input v-model="invoices[index-1]">
</div>
</div>
&#13;
更好的做法是invoices
一个对象数组,每个对象都有自己的id
和value
。这样,您可以呈现整个invoices
数组(通过v-for="invoice in invoices"
),而无需跟踪任何索引。这也允许您为每个渲染元素提供唯一的key
attribute:
new Vue({
el: '#app',
data() {
return {
invoices: [
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
{ id: 3, value: 'c' },
{ id: 4, value: 'd' }
]
}
}
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<div v-for="invoice in invoices" :key="invoice.id">
<input v-model="invoice.value">
</div>
</div>
&#13;