如何更新 vueJs 数组列表的特定行? [英] How to update a particular row of a vueJs array list?

查看:30
本文介绍了如何更新 vueJs 数组列表的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a proper way to refresh one particular row from a vueJS array list without reloading all the data?

在本例中,它是一个电话列表.

In this case, it is a phone list.

<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:这个代码只是为了演示问题.

PS: this is a code just to demonstrate the problem.

推荐答案

const currentIndex = this.phones.findIndex(p => p.id === id);
this.phones.splice(currentIndex, 1, updatedPhone)

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

If your target environment doesn't support findIndex on arrays, you can use some other means of finding the current index. One would be pass the phone instead of it's 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 都会检测到更改并为您重新渲染.

In both cases, Vue will detect the change and re-render for you.

这篇关于如何更新 vueJs 数组列表的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆