【问题标题】:How to iterate trough VueJS components and change attribute values如何遍历 Vue JS 组件并更改属性值
【发布时间】: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>

【问题讨论】:

  • 您是否尝试过在子组件中使用$attrsthis.$attrs 而不是$attr,顺便说一句,您似乎以正确的方式将:color="color" 传递给子组件
  • 专门访问child中的color属性:$attrs.colorthis.$attrs.color

标签: javascript node.js vue.js vuejs2


【解决方案1】:

在 Vue 中设置属性的适当方法是从子级到父级提供它们,而不干扰 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';
  }
}

但是在生产就绪的应用程序中我会在元素旁边提供颜色属性,因为在每次渲染时都会调用方法并且它不是最好的性能。

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

【讨论】:

  • 你的方式只是让它们变成绿色,如果我尝试使用重置按钮,它会给我一个键未定义的键错误,并且在我修改排序函数后,它只对数组的一个元素进行排序,但是对象的想法很好,因为我设法改变了我想要的颜色。
  • 当然,我不知道您打算使用的确切逻辑,所以这只是一个示例 :) 尝试使用:key="elem.n" 以确保您的密钥是唯一的
猜你喜欢
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 2019-07-25
  • 2011-01-16
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多