3

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.

2 Answers 2

7
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.

Sign up to request clarification or add additional context in comments.

Comments

3

You could use the built-in index generation:

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

And then in your edit function:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.