Updating Lists
Updating a list means changing the items in an array that Vue shows on the page. Vue watches the array and draws the page again when the array changes.
Add with push
push adds Cherry to the end of the list.
fruits.value.push('Cherry')Remove with splice
splice removes one item at position zero.
fruits.value.splice(0, 1)The list on the page
v-for draws one list item per fruit.
<li v-for="fruit in fruits" :key="fruit">{{ fruit }}</li>Example
<script setup>
import { ref } from 'vue'
const fruits = ref(['Apple', 'Banana'])
function addFruit() {
fruits.value.push('Cherry')
}
function removeFirst() {
fruits.value.splice(0, 1)
}
</script>
<template>
<div>
<ul>
<li v-for="fruit in fruits" :key="fruit">{{ fruit }}</li>
</ul>
<button @click="addFruit">Add Cherry</button>
<button @click="removeFirst">Remove first</button>
</div>
</template>
Key points
- The list lives in a ref array, so Vue can track its changes.
- The push method adds one item to the end of an array.
- The splice method removes items at a chosen spot in an array.
- Vue draws the list again after push or splice runs.
- A button with a click handler calls the function that changes the list.
In this example, fruits is a ref array with Apple and Banana. addFruit pushes Cherry onto the end of the array. removeFirst splices one item out at position zero. The template draws one list item per fruit with v-for and :key. Two buttons call the two functions. The first render shows Apple and Banana. A verified variant with Cherry added shows three items, and a variant after removing the first item shows Banana alone.
Note
Changing the array in place keeps the same ref, so Vue still sees the change.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method adds an item to the end of an array?