【问题标题】:Edit object of an array using Vue.JS使用 Vue.JS 编辑数组的对象
【发布时间】:2016-07-20 15:47:15
【问题描述】:

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

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

JS Bin

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

有人可以帮帮我吗?

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>

【问题讨论】:

    标签: javascript arrays object vue.js


    【解决方案1】:

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

       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

    【讨论】:

    • 这就是我要找的!谢谢维多维利!
    【解决方案2】:

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

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

    我们试试:JS Bin

    【讨论】:

    • 如果我有多个字段,有没有办法更轻松地为每个字段设置一个变量?对于一个字段表单,它可以完美运行,但是当您有一个更大的表单时,它会变得非常复杂!
    猜你喜欢
    • 1970-01-01
    • 2020-03-25
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2019-08-09
    • 2016-03-20
    • 2014-11-22
    相关资源
    最近更新 更多