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

Javascript + Vue: array failing to be reactive

I have the following code in a .vue file:

<template>
  <button @click="entries.push(3)">
    Press me!
  </button>
  <ul>
    <li v-for="entry in entries" :key="entry">
      {{ entry }}
    </li>
  </ul>
</template>

<script setup>
const entries = [1, 2]
</script>

After pressing the button I would expect a third li element to show up, yet nothing happens. What am I doing wrong?

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

>Solution :

I did a sandbox with the fix: https://codesandbox.io/s/beautiful-pond-8jg5zw?file=/src/App.vuee

<template>
  <button @click="entries.push(3)">Press me!</button>
  <ul>
    <li v-for="entry in entries" :key="entry">
      {{ entry }}
    </li>
  </ul>
</template>

<script setup>
import { ref } from "vue";

const entries = ref([1, 2]);
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Use the import { ref } from "vue";

Tip: Be aware of the difference between Ref and Reactive

https://vuejs.org/guide/essentials/reactivity-fundamentals.html#ref

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