vuejs for 循环总是返回最后一个值

问题描述 投票:0回答:2

在vuecli中我有这样的数据

data() {
        return {
            options: [{
                values: ['a', 'b', 'c']
            }],
            variants: [],
            p: {            
               option_1: null 
            }
        }
    }

当我在如下所示的方法中运行循环时

methods: {
  add() {
    for(let i = 0; i < this.options[0].values.length; i++) {

        (function(i, p){
            var raw = p;
            raw.option_1 = this.options[0].values[i]; 
            this.variants.push(raw); 
        })(i, this.p);

    } 
  }
}

我尝试了很多方法,但只有当我在循环中设置

raw
的值时才会成功,例如
var raw = {option_1: null}

但这不是我想要的。我想从

data
获取值并在循环中使用它来生成

variants: [{ option_1: 'a' }, { option_1: 'b' }, { option_1: 'c' }]

我怎样才能做到这一点?

javascript for-loop vuejs2
2个回答
1
投票

您需要

raw
的副本,因为
raw
中的
variants
只是指向同一对象的引用。这就是为什么你得到三个相同的值。

add() {
  let self = this
  for (let i = 0; i < self.options[0].values.length; i++) {
    (function (i, p) {
      var raw = p;
      raw.option_1 = self.options[0].values[i];
      self.variants.push(JSON.parse(JSON.stringify(raw)));
    })(i, self.p);
  }
  // this.options[0].values.forEach(v => {
  //     this.variants.push({ option_1: v })
  // })
}

注释中的代码是更优雅的方式。

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
  <mytag></mytag>
</div>
<script>
  let mytag = Vue.component("mytag", {
    template: `<div><button @click="add">add</button><p>this.variants:{{this.variants}}</p></div>`,
    data() {
      return {
        options: [{
          values: ["a", "b", "c"]
        }],
        variants: [],
        p: {
          option_1: null
        }
      };
    },
    methods: {
      add() {
        let self = this
        for (let i = 0; i < self.options[0].values.length; i++) {
          (function(i, p) {
            var raw = p;
            raw.option_1 = self.options[0].values[i];
            self.variants.push(Object.assign({}, raw));
            //self.variants.push(JSON.parse(JSON.stringify(raw)));
          })(i, self.p);
        }
        // this.options[0].values.forEach(v => {
        //     this.variants.push({ option_1: v })
        // })
      }
    }
  });
  new Vue({
    el: '#app',
    components: {
      mytag
    }
  })
</script>


0
投票

如果你希望最终结果看起来像这样

variants: [{
  option_1: 'a'
}, {
  option_1: 'b'
}, {
  option_1: 'c'
}]

如果每个条目均由

p
模板化,并将
option_1
设置为每个
values
条目,您可以使用

this.variants = this.options[0].values.map(option_1 => ({...this.p, option_1 }))

这会将 values 映射到带有键

option_1
的对象数组以及每个 values 项的值。


如果您想每次调用

add()
时添加 3 个对象,请将其更改为使用
Array.prototype.concat()

this.variants = this.variants.concat(
    this.options[0].values.map(option_1 => ({...this.p, option_1 })))
© www.soinside.com 2019 - 2024. All rights reserved.