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?

4
  • 3
    vue.js is still broken Commented Sep 7, 2019 at 14:04
  • well, react is much worse ! Commented Sep 7, 2019 at 14:30
  • 3
    Lack of understanding or knowledge in the subject doesn't mean it's necessarily broken. Commented Nov 27, 2019 at 14:13
  • 1
    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. Commented Jun 17, 2022 at 7:58

2 Answers 2

53

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>

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.