【问题标题】:How to update a particular row of a vueJs array list?如何更新 vueJs 数组列表的特定行?
【发布时间】:2017-04-07 17:33:56
【问题描述】:

有没有一种正确的方法可以在不重新加载所有数据的情况下从 vueJS 数组列表中刷新一个特定的行?

在这种情况下,它是一个电话列表。

<template>
    <table class="table">
        <tr v-for="phone in phones">
            <td @click="edit(phone.id)">
                {{phone.number}}
            </td>
            <td class="pointerCursor" @click="edit(phone.id)">
                {{phone.comment | truncate(90)}}
            </td>
        </tr>
    </table>
</template>

<script>
    export default {
        data () {
            return {
                phones = [
                    {id:1, number: '001 656 88 44', comment:''},
                    {id:2, number: '610-910-3575 x2750', comment:'Quod odit quia'},
                    {id:3, number: '536.224.2639 x714', comment:'primary phone'},
                    {id:5, number: '0034 556 65 77', comment:'home phone phone'},
                ]
            }
        },

        methods: {
            edit(id) {
                // update using an api that returns the updated data.
                var updatedPhone = update(id)

                // how to update with reloading all the phone list?
                // ...
            }
        }
    }
</script>

PS:这段代码只是为了演示问题。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:
    const currentIndex = this.phones.findIndex(p => p.id === id);
    this.phones.splice(currentIndex, 1, updatedPhone)
    

    如果您的目标环境不支持数组上的 findIndex,您可以使用其他一些方法来查找当前索引。一种是通过电话而不是它的 id。

    edit(phone) {
        const currentIndex = this.phones.indexOf(phone);
    
        // update using an api that returns the updated data.
        var updatedPhone = update(phone.id)
    
        this.phones.splice(currentIndex, 1, updatedPhone)
    }
    

    在这两种情况下,Vue 都会检测到更改并为您重新渲染。

    【讨论】:

      【解决方案2】:

      您可以使用内置的索引生成:

          <tr v-for="(phone, index) in phones">
              <td @click="edit(index)">
                  {{phone.number}}
              </td>
              <td class="pointerCursor" @click="edit(index)">
                  {{phone.comment | truncate(90)}}
              </td>
          </tr>
      

      然后在你的编辑功能中:

          methods: {
              edit(index) {
                  phone = this.phones[index];
      
                  // update using an api that returns the updated data.
                  var updatedPhone = update(phone.id)
      
                  // how to update with reloading all the phone list?
                  this.phones.splice(index, 1, updatedPhone)
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2017-07-31
        • 1970-01-01
        • 2016-08-28
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 2013-11-21
        • 2017-11-30
        • 2021-03-26
        相关资源
        最近更新 更多