vue 解决input内值的双向绑定问题

在使用vue进行双向绑定的时候,第一想到的肯定是官方语法{{msg}},但是在input中如果这样想,那就错啦。

错误的写法如下:<input type="text" value="{{item.age}}" />

既然这种写法是错误的,那么怎样才能实现在input中的数据双向绑定呢?方法如下:

用v-model进行绑定

<input type="text" v-model="item.count" readonly="readonly"/>

具体代码可见:https://download.csdn.net/download/colourfultiger/10515153

大体描述如下:

1、遍历显示的数据

data() {
return {
//   购物清单
list: [{
id: 1,
name: '铅笔',
price: 180,
count: 1,
Stotal:180
},
{
id: 2,
name: '书包',
price: 200,
count: 1,
Stotal:200
},
{
id: 3,
name: '衣服',
price: 500,
count: 1,
Stotal:500
}
]
}

},

2、html写法

<tr v-for="(item,index) in list">
<td>{{ index + 1}}</td>
<td>{{ item.name }}</td>
<td>¥{{ item.price }}</td>
<td>
<button @click="handleReduce(index)" :disabled="item.count===1">-</button>
<input type="text" v-model="item.count" readonly="readonly"/>
<button @click="handleAdd(index)">+</button>
</td>
<td>¥{{ item.Stotal }}</td>
<td>
<el-button @click="handleRemove(index)" type="danger" icon="el-icon-delete" circle></el-button>
</td>
</tr>
<tr>
<td colspan="4"></td>
<td colspan="2">总价 :¥{{totalPrice}}</td>

</tr>

3、函数处理部分:

methods: {
handleReduce: function(index) {
if(this.list[index].count === 1) return;
this.list[index].count--;
this.list[index].Stotal = this.list[index].price * this.list[index].count;
},
handleAdd: function(index) {
this.list[index].count++;
this.list[index].Stotal = this.list[index].price * this.list[index].count;
},
handleRemove: function(index) {
this.list[index].splice(index, 1);
}
},
computed: {
//总计
totalPrice: function() {
var total = 0;
for(var i = 0; i < this.list.length; i++) {
var item = this.list[i];
total += item.price * item.count;
}
return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');

}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值