繁体   English   中英

如何遍历 VueJS 组件并更改属性值

[英]How to iterate trough VueJS components and change attribute values

我正在尝试使用 VueJS 为排序算法构建可视化。 以冒泡排序为例,我设法让一切正常工作。 我只想更改排序发生时比较的元素的颜色。 我的 Bar 元素有一个颜色 porp,我想在我的气泡排序函数循环中更改它,以便每当一个元素与另一个元素进行比较时,一个元素变为蓝色和一个绿色,比较结束后下一个元素变为蓝色和绿色,依此类推。

问题是:如何遍历 Bar 元素并更改颜色属性?

我已经尝试过在 vanilla JS 中使用 getAttribute() 但它不适用于 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>

在 Vue 中设置属性的适当方法是将它们从 child 提供给 parent,而不干扰 setAttribu 最直接的方法是基于 elem 动态获取颜色。
像这样的事情会做:

<Bar v-for="elem in array" v-bind:key="elem" :color="getColor(elem)" :value="elem" class="elem" />

methods: {
  getColor(elem) {
    return elem > 0.5 ? 'red' : 'green';
  }
}

然而,在生产就绪的应用程序中,我会提供 color 属性和 element ,因为在每次渲染时都会调用 method 并且它不是最好的性能。

    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, color: n > 0.5 ? 'red' : 'green'});
        }
      }
    },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM