Javascript vuejs数据更新,但更改不会反映在模板中
这是我的模板Javascript vuejs数据更新,但更改不会反映在模板中,javascript,sorting,vue.js,Javascript,Sorting,Vue.js,这是我的模板 <template> <div class="array_bars"> <div class="array_bar_wrapper"> <div v-for="(h, index) in heights" :key="index" class="each_bar" v-bind:style="{ height: h + 'px' }"></div> </div> &
<template>
<div class="array_bars">
<div class="array_bar_wrapper">
<div v-for="(h, index) in heights" :key="index" class="each_bar" v-bind:style="{ height: h + 'px' }"></div>
</div>
<div class="action-buttons">
<button @click="resetArray">Reset</button>
<button @click="bubbleSort">Bubble Sort</button>
<button @click="sort">Sort</button>
</div>
</div>
</template>
重置
气泡排序
分类
这是剧本
export default {
name: 'SortingVisualizer',
data() {
return {
heights: [],
totalBars: 100,
}
},
methods: {
getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
},
resetArray() {
this.heights = [];
for(let i=0; i<this.totalBars; i++) {
this.heights.push(this.getRandomInt(2, 400));
}
},
bubbleSort() {
for(let i=0; i<this.heights.length; i++) {
for (let j=0; j<(this.heights.length-i-1); j++) {
if(this.heights[j]>this.heights[j+1]) {
let temp = this.heights[j];
this.heights[j] = this.heights[j+1];
this.heights[j+1] = temp;
}
}
}
console.log(this.heights);
},
sort() {
this.heights.sort((a, b) => a-b);
console.log(this.heights);
},
},
mounted() {
for(let i=0; i<this.totalBars; i++) {
this.heights.push(this.getRandomInt(2, 400));
}
},
}
导出默认值{
名称:“SortingVisualizer”,
数据(){
返回{
高度:[],
总杆数:100,
}
},
方法:{
getRandomInt(最小值、最大值){
min=数学单元(min);
最大值=数学楼层(最大值);
返回Math.floor(Math.random()*(max-min+1))+min;
},
resetArray(){
this.heights=[];
for(设i=0;i在更改数组中的值时使用)
Vue.set(this.heights, j, this.heights[j+1]);
Vue.set(this.heights, j+1, tmp);
或者复制阵列,对副本进行排序,然后将其分配给this.height
。这也会起作用。您在vue中遇到了反应性限制之一。请看它现在是否起作用,顺便说一句i
应该是j+1
。在这种情况下,谢谢,更改了它。