1. 程式人生 > >vue 解決input內值的雙向繫結問題

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, ',');

}