vuejs обновления данных, но изменение не отражается в шаблоне - PullRequest
0 голосов
/ 16 апреля 2020

Это мой шаблон

<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 Ответ

1 голос
/ 16 апреля 2020

Используйте Vue .set при изменении значений в массиве.

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

Или скопируйте массив, отсортируйте копию и затем присвойте ее this.height. Это также будет работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...