输入字段未更新数组中的"address"



我正在创建一个表,该表通过数组循环并将表中的数组显示为列表。我将地址显示为输入字段值: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>

请让我知道我做错了什么,或者是否有更好的方法来解决它

您的输入字段绑定到location.address。所以,你根本没有编辑你的editedAddress

你可以添加@change="editedAddress = $event.target.value"到你的输入字段来改变editedAddress

<input type="text" :value="location.address" :disabled="location.disabled" @change="editedAddress = $event.target.value" >

提示:使用Vue开发工具或JSON。Stringify检查vue应用程序中的数据

JSON.stringify(editedAddress): {{JSON.stringify(editedAddress)}}

这是带有修复

的链接游乐场

既然你没有解释你到底是什么意思;我已经为更新按钮添加了以下代码,但它不起作用"我将假定您的UI没有更新。

这是Vue反应系统反应性的一个警告https://v2.vuejs.org/v2/guide/reactivity.html#For-Arrays

可能Vue无法选择数组locations中的项发生了变化。

你可以使用Vue.set:

btnUpdate(index){
Vue.set(this.locations[index], 'address', this.editedAddress);
// do the same for the other line
},

在此之后,我们应该能够选择有一个变化,并重新渲染UI。

另一种方法是替换整个数组(但在大多数情况下这有点过分)

btnUpdate(index){
const locations = [...this.locations];

locations[index].address = this.editedAddress;
this.locations = locations;
},

最新更新