methods 的 add 方法有两种写法,结果是 v-model 的表现结果第一种写法是正常的,第二种就不对,求解原因
第一种写法的效果图:
第二种写法的效果图:
<template>
<div style="width:100%;overflow:hidden;">
<ul class="list">
<li v-for="(item, index) in arrs">
<input
type="number"
v-model="item.customItem"
@input="changeFunc(item, index)"
/>
</li>
</ul>
<button @click="newadd">新增一项</button>
</div>
</template>
<script>
export default {
data () {
return {
arrs: [{
'value': 1,
'customItem': 1
},{
'value': 2,
'customItem': 2
}],
na: {
value: '',
customItem: ''
}
}
},
methods: {
newadd() {
newadd() {
// 这样写是正常的
// this.arrs.push({
// value: '',
// customItem: ''
// });
// 这样写 v-model 就不对了
this.arrs.push(this.na);
console.log(this.na)
},
changeFunc(item, index) {
this.arrs[index].customItem = item.customItem;
this.watchVal();
},
// 监听值的变化
watchVal() {
const arrs = this.arrs;
if (arrs.length > 0) {
for (let i = 0; i < arrs.length; i++) {
let customItem = arrs[i].customItem;
if (customItem * 1 < 0) {
this.$set(this.arrs[i], 'customItem', 0);
}
}
}
}
}
}
</script>
因为你添加的是同一个对象