vue3 data change does not re-render html

I am new to Vue. I have a simple vue3 script, (using cdn, not npm).

index.html

<div id="app">
  <h2>{{ title }}</h2>
  <ul>
    <li v-for="item in items">{{ item }}</li>
  </ul>
</div>

<script src="https://unpkg.com/vue@3.3.4/dist/vue.runtime.global.prod.js"></script>
<script src="app.js"></script>

app.js

const { createApp, ref } = Vue;

createApp({
  setup() {
    const title = ref('Fruits');
    const items = ['apple', 'orange', 'banana'];

    return { title, items };
  }
}).mount('#app');

This works fine and I get both the title and items populated in html.
The only issue is the component never re-renders when data is changed. To simulate data change, I have added a timer to add an item to the array:

createApp({
     setup() {
        const title = ref('Fruits');
        const items = ['apple', 'orange', 'banana'];

        setTimeout( () => items.push('grapes'), 4000 );  // this has no effect

        return { title, items };
      }
 }).mount('#app');

The timer executes, the array is appended, but the html is never updated.

What am I doing wrong?

>Solution :

Your array is not reactive.

createApp({
     setup() {
        const title = ref('Fruits');
        const items = ref(['apple', 'orange', 'banana']); // Made reactive

        setTimeout( () => items.value.push('grapes'), 4000 );  // use value to access the instance

        return { title, items };
      }
 }).mount('#app');

Leave a Reply