阅读:6030回复:0
vue 解决input内值的双向绑定问题
在使用vue进行双向绑定的时候,第一想到的肯定是官方语法{{msg}},但是在input中如果这样想,那就错啦。
错误的写法如下:<input type="text" value="pw_item.age" /> 既然这种写法是错误的,那么怎样才能实现在input中的数据双向绑定呢?方法如下: 用v-model进行绑定 <input type="text" v-model="item.count" readonly="readonly"/> 大体描述如下: 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>pw_ index + 1</td> <td>pw_ item.name </td> <td>¥pw_ 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>¥pw_ 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">总价 :¥pw_totalPrice</td> </tr>3、函数处理部分: [code ]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; total += item.price * item.count; } return total.toString().replace(/\B(?=(\d{3})+$)/g, ','); }[/code] |
|