vuejs数据更新,但更改未反映在模板中

时间:2020-04-16 13:52:14

标签: 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>

    <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));
        }
    },
}

当我单击sort按钮时,一切正常工作和更改都会反映在使用内置排序方法的模板中。

但是,当我单击bubbleSort按钮时,随机生成的高度将被排序(在控制台中),但是更改未反映在模板中。为什么?

1 个答案:

答案 0 :(得分:1)

更改数组中的值时,请使用Vue.set

Vue.set(this.heights, j, this.heights[j+1]);
Vue.set(this.heights, j+1, tmp);

或复制数组,对副本进行排序,然后将其分配给this.height。这也将起作用。

相关问题