如何更新 vueJs 数组列表的特定行?

2024-03-13

有没有一种正确的方法可以刷新 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:这只是为了演示问题的代码。


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

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

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 都会检测到更改并为您重新渲染。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何更新 vueJs 数组列表的特定行? 的相关文章

随机推荐