Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a particular row of a vueJs array list?

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: this is a code just to demonstrate the problem.

like image 809
Warrio Avatar asked Dec 17 '25 21:12

Warrio


1 Answers

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

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)
}

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

like image 53
Bert Avatar answered Dec 20 '25 11:12

Bert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!