Clearing an array content and reactivity issues using Vue.js
Asked Answered
W

2

24

A few years ago it was bad practice to do

array = [];

because if the array was referenced somewhere that reference wasn't updated or something like that.

The correct way was supposed to be array.length = 0;

Anyway, JavaScript has been updated now, and there's a framework called Vue.js

Vue does not catch array.length = 0; so the property won't be reactive. But it does catch array = [];

Can we use array = []; now, or is JavaScript still broken?

Weddle answered 7/9, 2019 at 14:0 Comment(4)
vue.js is still brokenBrouhaha
well, react is much worse !Weddle
Lack of understanding or knowledge in the subject doesn't mean it's necessarily broken.Colure
To clarify for others new to JavaScript, this question is very badly written and be careful when reading it. First, JavaScript is not broken. Second, JavaScript was not 'updated' to have Vue, it's simply a framework. Third, the 'losing reference if doing = [], is by design and is not something broken. Can't simply explain why it does that in this comment but learn about it please. As for the "if it's referenced somewhere" literally where you are using it is a reference. How JavaScript stores and references things is basic JS 101, and very very useful to FULLY understand. Read up asap.Astrahan
T
52

Doing something like myArray.splice(0) will clear the content of the array and that will also be reactive:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',

  data() {
    return {
      items: ["a", "b", "c"]
    }
  },
  methods: {
    flush() {
      this.items.splice(0);
    }
  }

});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">

  <div v-for="i in items">{{i}}</div>

  <button @click="flush"> flush</button>
</div>
Tactician answered 7/9, 2019 at 14:8 Comment(0)
R
12

Vue cannot detect the following changes to an array: When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue When you modify the length of the array, e.g. vm.items.length = newLength

From: Reactivity in Depth, For Arrays

So, cleaning a reactive array:

yourArray.splice(0)
Rumen answered 24/6, 2021 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.