【发布时间】:2020-07-01 11:08:40
【问题描述】:
我正在尝试使用 VueJS 为排序算法构建可视化。以冒泡排序为例,我现在设法让一切正常。我只想更改排序发生时比较的元素的颜色。我的 Bar 元素有一个颜色孔,我想在我的 bubbleSort 函数循环中更改它,以便每当将一个元素与另一个元素进行比较时,一个元素变为蓝色和一个绿色,比较结束后,下一个元素变为蓝色和绿色,依此类推。
问题是:如何迭代 Bar 元素并更改颜色属性?
我已经尝试过 getAttribute() ,就像在 vanilla JS 中一样,但它不适用于 VueJS,我尝试过使用 $attr 但它说它未定义。
<template>
<div class="main">
<div class="menu-bar">
<button v-on:click="bubbleSort">Sort</button>
<button v-on:click="arrayPopulate">Reset</button>
</div>
<div class="elements">
<Bar v-for="elem in array" v-bind:key="elem" :color="color" :value="elem" class="elem" />
</div>
</div>
</template>
<script>
import * as HF from "../algorithms/helperfunctions";
import Bar from "./Bar.vue";
export default {
name: "Element",
components: {
Bar
},
data() {
return {
array: [],
color: "red",
current: "blue",
comparing: "green"
};
},
methods: {
arrayPopulate() {
this.array = [];
for (let i = 0; i < 40; i++) {
let n = Math.floor(Math.random() * 100 + 10);
if (!this.array.includes(n)) {
this.array.push(n);
}
}
},
async bubbleSort() {
//let elements = document.getElementsByTagName("Bar");
let len = this.array.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (this.array[j] > this.array[j + 1]) {
HF.arraySwap(this.array, j + 1, j);
await HF.sleep();
}
}
}
return this.array;
}
},
created() {
this.arrayPopulate();
}
};
</script>
【问题讨论】:
-
您是否尝试过在子组件中使用
$attrs或this.$attrs而不是$attr,顺便说一句,您似乎以正确的方式将:color="color"传递给子组件 -
专门访问child中的color属性:
$attrs.color或this.$attrs.color
标签: javascript node.js vue.js vuejs2