Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading