gpt4 book ai didi

javascript - 使用 Vue.JS 编辑数组对象

转载 作者:搜寻专家 更新时间:2023-10-30 22:56:09 25 4
gpt4 key购买 nike

我正在使用 Vuejs + Laravel 开发我的第一个应用程序,我遇到了一个直到现在我都无法解决的问题!

我有一个对象数组,我需要编辑其中一个而不删除并添加一个新对象!我做了一个JS Bin来展示我需要的东西!

JS Bin

当您单击“编辑”并开始输入新值时,原始值也会进行编辑,但我只需要在用户点击保存按钮后更改原始值!

谁能帮帮我?

PS:我会更新我的数据库,然后在表上显示新值!

有没有像我在没有同步的编辑功能上所做的那样复制我的记录?

JS

new Vue({

el: 'body',

data: {
cache: {},
record: {},
list: [
{ name: 'Google', id: 1 },
{ name: 'Facebook', id: 2 },
],
},

methods: {
doEdit: function (record) {
this.cache = record;
},
edit: function (record) {
this.record = _.cloneDeep(record);
this.cache = record;
}
}

});

HTML

<div class="container">

<form class="form-horizontal" @submit.prevent="doEdit(record)">
<div class="row">
<div class="col-md-12">
<label>Name</label>
<input type="text" class="form-control" v-el:record-name v-model="record.name">
</div>
<div class="col-xs-12" style="margin-top:15px">
<button type="submit" class="col-xs-12 btn btn-success">Save</button>
</div>
</div>
</form>
<hr>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="r in list">
<td class="text-center" style="width:90px"> {{ r.id }} </td>
<td> {{ r.name }} </td>
<td class="text-center" style="width:90px">
<span class="btn btn-warning btn-xs" @click="edit(r)"><i class="fa-fw fa fa-pencil"></i></span>
</td>
</tr>
</tbody>
</table>
</div>

最佳答案

您可以用克隆更新的对象替换旧对象。

   doEdit: function (record) {
var index = _.indexOf(this.list, this.cache);
this.list.splice(index, 1, record);
}

https://jsbin.com/ruroqu/3/edit?html,js,output

关于javascript - 使用 Vue.JS 编辑数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36346123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com