我正在創建一個表,它回圈遍歷一個陣列并將表中的陣列顯示為串列。我將地址顯示為輸入欄位值:value="location.address"
輸入欄位設定為禁用,當我單擊編輯按鈕時,我將禁用屬性更新為 false,以便可以編輯輸入欄位。我添加了一個名為的新屬性editedAddress: null并將其設定為 null,該屬性更新為當前地址屬性this.editedAddress = this.locations[index].address。
我想要的是當我點擊編輯按鈕時,我想要更新地址。我為更新按鈕添加了以下代碼,但它不起作用。
btnUpdate(index){
this.locations[index].address = this.editedAddress;
this.locations[index].disabled = !this.locations[index].disabled
}
這是完整的代碼
<template>
<div>
<table>
<tr>
<th>#</th>
<th>Locations</th>
<th>Actions</th>
</tr>
<tr v-for="(location, index) in locations" :key="index">
<td>{{index 1}}</td>
<td>
<input type="text" :value="location.address" :disabled="location.disabled">
</td>
<td>
<div class="action-btns">
<button @click="btnEdit(index)">Edit</button>
<button @click="btnUpdate(index)">Update</button>
<button @click="btnDelete(index)">Delete</button>
</div>
</td>
</tr>
</table>
<input type="text" v-model="address">
<button @click="addBtn">Add</button>
</div>
</template>
<script>
export default {
data(){
return{
locations:[
{
address:'Mall of lahore',
disabled: true
},
{
address: 'The Post Office',
disabled: true
},
{
address: 'Mall of Dubai',
disabled: true
}
],
address: '',
editedAddress: null
}
},
methods:{
btnEdit(index){
this.locations[index].disabled = !this.locations[index].disabled
this.editedAddress = this.locations[index].address
},
btnUpdate(index){
this.locations[index].address = this.editedAddress;
this.locations[index].disabled = !this.locations[index].disabled
},
btnDelete(index){
this.locations.splice(index , 1)
},
addBtn(){
let newAddress = {
address: this.address,
disabled: true
}
this.locations.push(newAddress)
this.address = '';
}
}
}
</script>
請讓我知道我做錯了什么或者是否有更好的方法來解決它
uj5u.com熱心網友回復:
您的輸入欄位系結到location.address. 所以,你根本沒有編輯你editedAddress的。
您可以添加@change="editedAddress = $event.target.value"到您的輸入欄位進行更改editedAddress
<input type="text" :value="location.address" :disabled="location.disabled" @change="editedAddress = $event.target.value" >
提示:使用Vue Dev Tools或 JSON.stringify 檢查你的 vue 應用程式中的資料
JSON.stringify(editedAddress): {{JSON.stringify(editedAddress)}}
這是帶有修復程式的鏈接游樂場
uj5u.com熱心網友回復:
由于您沒有解釋“我為更新按鈕添加了以下代碼但它不起作用”究竟是什么意思,我將假設您的 UI 沒有更新。
這是 Vue 反應式系統中反應性的警告https://vuejs.org/v2/guide/reactivity.html#For-Arrays
可能 Vue 無法發現您的專案在 array 中發生了變化locations。
要讓 Vue 了解您可以使用Vue.set以下更改:
btnUpdate(index){
Vue.set(this.locations[index], 'address', this.editedAddress);
// do the same for the other line
},
在此之后 Vue 應該能夠選擇有更改并為您重新渲染 UI。
另一種方法是替換整個陣列(但在大多數情況下這有點矯枉過正)
btnUpdate(index){
const locations = [...this.locations];
locations[index].address = this.editedAddress;
this.locations = locations;
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324815.html
標籤:javascript 数组 Vue.js Vuejs3
