[英]method in Vue.js cannot alter data value
我正在使用 Vue.js 2 並且我正在嘗試制作一個在用戶輸入后進行簡單折扣計算的組件。
我使用的 object 作為起始數據是這樣制作的 object:它由幾個建築物組成,每個建築物里面可以有幾個房間。 我有一個 object (我把它寫成一個數組,但它是一個對象)誰有
buildings[<building_id>][<room_id]={room_id: <room_id>,
building_id: <building_id>
name: <name>,
price: <regular_price>
discounted_price: <discounted_price>
discount: discount}
這是組件的完整代碼
<template>
<div>
{{ buildings }}
<li v-for="(building, k) in buildings" :key="k">
<table class="table table-striped table-bordered">
<thead>
<tr><th>Room</th><th>Standard price</th><th>Discounted price</th><th>Discount</th></tr>
</thead>
<tbody>
<tr v-for="(room, s) in building" :key="s">
<td>{{room.name}}</td>
<td>{{room.price}} €</td>
<td><input type="text" class="form-control" v-model="room.discounted_price"
@input="calcDiscount(room)"></td>
<td><input type="text" class="form-control" v-model="room.discount" disabled></td>
</tr>
</tbody>
</table>
</li>
</div>
</template>
<script>
export default {
data: function() {
return {
buildings: {},
}
},
mounted() {
this.getBuildings();
},
methods: {
getBuildings: function(callback) {
httpRequest(api_url + "get/buildings").then(onResult => {
this.buildings = onResult.data.buildings;
});
},
calcDiscount(evt) {
room.discount = Math.round(
100 - (100 * room.discounted_price) / room.price
);
}
}
}
</script>
這段代碼有兩個問題。 首先,輸入元素上的 v-bind 不起作用。 如您所見,我在頂部打印了buildings
object 並且我沒有看到用戶輸入的discounted_price
的值發生變化。
但除此之外,盡管日志顯示正確的值,但 object 中的discount
和discounted_price
的值都沒有改變。 但是這些值是正確的,因為它們之前只打印了一行。 我做錯了什么? 謝謝
陶評論后編輯
進一步更新:由於在操場上制作的代碼 tao 有效,問題應該出在我的環境中。 顯然 function calcDiscount
工作得很好,因為如果我打印 function 里面的值,它就會正確打印。 但不知何故,當 function 存在時,這些變化消失了。 會不會是事件發生在不同的空間?
您需要通過v-on:keyup
更改@input
。 輸入綁定只是更改內部的值,但它不會使 web 應用程序認識到它需要重新渲染。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.