苍穹
管理员
管理员
  • UID2
  • 粉丝0
  • 关注0
  • 发帖数202
阅读:5174回复:0

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

楼主#
更多 发布于:2018-08-30 20:19
在使用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写法



&lt;tr v-for="(item,index) in list"&gt;
&lt;td&gt;pw_ index + 1&lt;/td&gt;
&lt;td&gt;pw_ item.name &lt;/td&gt;
&lt;td&gt;¥pw_ item.price &lt;/td&gt;
&lt;td&gt;
&lt;button @click="handleReduce(index)" :disabled="item.count===1"&gt;-&lt;/button&gt;
&lt;input type="text" v-model="item.count" readonly="readonly"/&gt;
&lt;button @click="handleAdd(index)"&gt;+&lt;/button&gt;
&lt;/td&gt;
&lt;td&gt;¥pw_ item.Stotal &lt;/td&gt;
&lt;td&gt;
&lt;el-button @click="handleRemove(index)" type="danger" icon="el-icon-delete" circle&gt;&lt;/el-button&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td colspan="4"&gt;&lt;/td&gt;
&lt;td colspan="2"&gt;总价 :¥pw_totalPrice&lt;/td&gt;
 
&lt;/tr&gt;
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 &lt; this.list.length; i++) {
var item = this.list;
total += item.price * item.count;
}

return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');
 
}[/code]
游客


返回顶部