使用 Vue.js 清除阵列内容和反应性问题
Clearing an array content and reactivity issues using Vue.js
几年前这样做是不好的做法
array = [];
因为如果数组在某处被引用,则该引用未更新或类似的东西。
正确的方法应该是array.length = 0;
反正JavaScript已经更新了,还有一个框架叫Vue.js
Vue 不会捕获 array.length = 0;
,因此 属性 不会响应。但它确实抓住了 array = [];
我们现在可以使用 array = [];
,还是 JavaScript 仍然损坏?
像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, e.g. vm.items[indexOfItem] = newValue When
you modify the length of the array, e.g. vm.items.length = newLength
发件人:Reactivity in Depth, For Arrays
因此,清理反应阵列:
yourArray.splice(0)
几年前这样做是不好的做法
array = [];
因为如果数组在某处被引用,则该引用未更新或类似的东西。
正确的方法应该是array.length = 0;
反正JavaScript已经更新了,还有一个框架叫Vue.js
Vue 不会捕获 array.length = 0;
,因此 属性 不会响应。但它确实抓住了 array = [];
我们现在可以使用 array = [];
,还是 JavaScript 仍然损坏?
像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, e.g. vm.items[indexOfItem] = newValue When you modify the length of the array, e.g. vm.items.length = newLength
发件人:Reactivity in Depth, For Arrays
因此,清理反应阵列:
yourArray.splice(0)