javascript - 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' }]
我怎样才能做到这一点?
解决方案
您需要一个副本,raw
因为raw
invariants
只是指向同一对象的引用。这就是为什么你得到三个相同的值。
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>
最后,你最好学习一些关于如何提问的知识!
推荐阅读
- android - 转到该片段后,底部导航栏仍处于选中状态
- python - Python根据第一列中的键组合两列
- vim - 用VIM在C中应用“尤达条件”的最短方法是什么
- ios - 无法检索额外的标头 - Mailcore
- javascript - 悬停时在相对标签内滚动绝对图像
- javascript - 从 javascript 打开页面不起作用
- django - IndentationError: unindent 不匹配任何外部缩进级别 django
- python - 验证 Django 时间
- nativescript - 如何将数组数组传递给Java函数?
- mongodb - 如何在 bluemix 上使用 nodered 配置 mongodb?