Vue Not Updating When Changing Array

July 11th, 2021

Warning: This post is 3 years old. Some of this information may be out of date.

Have you ever had a problem with Vue.js not updating when changing the contents of an array? You have? Great! I know just how to fix that.

Here's a small Vue component with an array of items defined:

<template>
    <div>
        <ul>
            <li v-for="item in items" v-html="item"></li>
        </ul>
        <button @click="addThree">Add 'Three'</button>
    </div>
</template>

<script>
export defaults {
    name: 'MyComponent',
    data () {
        return {
            items: ['One', 'Two']
        }
    },

    methods: {
        addThree () {
            this.items[2] = 'Three';
        }
    }
}
</script>

When running the above code you would see an unordered list with 'One' and 'Two'. When you click on the 'Add Three' button you would expect to see 'Three' appended to the list.

But it doesn't get added.

This is because there's no way with vanilla JavaScript to detect a change to an array. Instead, you need to use a Vue specific set() method to update the array:

addThree() {
    // (reference array, index, value)
    Vue.set(this.items, 2, 'Three');
}