1
美好的一天,我正在與Vuejs進行簡單的內聯編輯功能。請看看這個jsbin。vuejs內聯編輯選擇框選項呼叫問題
用戶信息。與Edit
按鈕列出,當點擊時,我把它們變成輸入/選擇字段,並用輔助方法填充相應的選項。
我的問題在這裏有一次我填充選擇選項,我的幫助方法被稱爲即使我改變選擇值。我怎樣才能改變它只加載一次並使用它們。另外,如何在點擊save
按鈕時根據需要驗證當前行字段?
美好的一天,我正在與Vuejs進行簡單的內聯編輯功能。請看看這個jsbin。vuejs內聯編輯選擇框選項呼叫問題
用戶信息。與Edit
按鈕列出,當點擊時,我把它們變成輸入/選擇字段,並用輔助方法填充相應的選項。
我的問題在這裏有一次我填充選擇選項,我的幫助方法被稱爲即使我改變選擇值。我怎樣才能改變它只加載一次並使用它們。另外,如何在點擊save
按鈕時根據需要驗證當前行字段?
試試這個。
new Vue({
el: '#app',
data: {
users: [
{name: 'Jhon', city:'Newyork', country: 'US', country_id:'23', city_id:'4'},
{name: 'Ali', city:'London', country: 'UK', country_id:'13', city_id:'33'},
{name: 'Raj', city:'Delhi', country: 'IN', country_id:'3', city_id:'11'},
],
cities: [
{id:'4', val:'Newyork', country_id:'23'},
{id:'33', val:'London', country_id:'13'},
{id:'11', val:'Delhi', country_id:'3'},
],
countries: [
{id:'23', val:'US'},
{id:'13', val:'UK'},
{id:'3', val:'IN'},
]
},
computed:{
citiesByCountry(){
return this.countries.reduce((acc, country) => {
acc[country.id] = this.cities.filter(c => c.country_id == country.id)
return acc
}, {})
}
},
methods: {
edit :function(obj){
this.$set(obj, 'editmode', true);
},
save : function(obj){
this.$set(obj, 'editmode', false);
},
cloneLast:function(){
var lastObj = this.users[this.users.length-1];
lastObj = JSON.parse(JSON.stringify(lastObj));
lastObj.editmode = true;
this.users.push(lastObj);
},
}
})
然後將您的模板更改爲此。
<td>
<span v-if="user.editmode">
<select v-model="user.city_id" required>
<option v-for="option in citiesByCountry[user.country_id]" :value="option.id">{{option.val}}</option>
</select>
</span>
<span v-else>{{user.city}}</span>
</td>
<td>
<span v-if="user.editmode">
<select v-model="user.country_id" required>
<option v-for="option in countries" :value="option.id">{{option.val}}</option>
</select>
</span>
<span v-else>{{user.country}}</span>
</td>
工作example。
謝謝你的建議。但是,實際上城市的選擇取決於所選擇的國家。它會發送一個Ajax請求到服務器獲取城市列表。我不能將它們存儲爲靜態對象。對不起,不清楚。 –
@NareshRevoori然後使其成爲一個計算。 – Bert
請看看http://jsbin.com/vevivesena/edit?html,js,output –