简体   繁体   English

使用 Vue.js 清除数组内容和反应性问题

[英]Clearing an array content and reactivity issues using Vue.js

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;正确的方法应该是array.length = 0;

Anyway, JavaScript has been updated now, and there's a framework called Vue.js反正现在 JavaScript 已经更新了,还有一个叫 Vue.js 的框架

Vue does not catch array.length = 0; Vue 没有捕获array.length = 0; so the property won't be reactive.所以该属性不会是反应性的。 But it does catch array = [];但它确实捕获了array = [];

Can we use array = [];我们可以使用array = []; now, or is JavaScript still broken?现在,还是 JavaScript 仍然损坏?

Doing something like myArray.splice(0) will clear the content of the array and that will also be reactive:执行myArray.splice(0)之类的操作将清除数组的内容,这也是反应性的:

 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>

Vue cannot detect the following changes to an array: When you directly set an item with the index, eg vm.items[indexOfItem] = newValue When you modify the length of the array, eg vm.items.length = newLength Vue 无法检测到数组的以下变化: 当你直接设置一个带有索引的项目时,例如 vm.items[indexOfItem] = newValue 当你修改数组的长度时,例如 vm.items.length = newLength

From: Reactivity in Depth, For Arrays来自:深度反应性,对于数组

So, cleaning a reactive array:所以,清理一个反应数组:

yourArray.splice(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM