首页 > 解决方案 > vuejs for 循环总是返回最后一个值

问题描述

在 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' }]

我怎样才能做到这一点?

标签: javascriptfor-loopvuejs2

解决方案


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

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>

最后,你最好学习一些关于如何提问的知识!


推荐阅读