使用Vue.JS编辑数组的对象

Edit object of an array using Vue.JS

本文关键字:对象 数组 编辑 Vue JS 使用      更新时间:2023-11-11

我正在使用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,输出

如果只想在用户提交后保存值,则不应直接绑定记录,如v-model="record.name"

我们可以使用Vue.set来更改原始记录的属性。

让我们试试:JS Bin