我对 Vue 非常陌生,对于一个项目,我试图根据数字创建一组对象。例如,如果总长度值为3,那么有没有办法创建fetchList1
、fetchList2
和fetchList3
?如果总长度值为 2,则应创建数据返回对象为 fetchList1
和 fetchList2
。
我从数据库中获取总长度值,因此它有时会大于 50,有时会小于 5。
查看
<div id="app">
<button @click="grabTeams()">
CLICK ME
</button>
</div>
方法
new Vue({
el: "#app",
data: {
totalLength: '3',
fetchList1: '',
/** if the total length is 3 then it should automatically create fetchList1, fetchList2 and fetchList3 **/
},
methods: {
toggle: function(todo){
todo.done = !todo.done
},
grabTeams(){
console.log('Total value length ' +this.totalLength);
for(let b=0; b < this.totalLength; b++){
console.log('value of '+b);
var replyDataObj1 = parseInt(b);
replyDataObj1={
"id" : b
}
this['fetchList'+b] = replyDataObj1;
}
},
}
})
下面是我在 jsfiddle 上尝试过的链接
最佳答案
如果您尝试动态添加根数据属性,Vue 将抛出警告。来自 docs :
Vue does not allow dynamically adding new root-level reactive properties to an already created instance.
相反,创建一个 fetchList
数组:
data() {
return {
fetchList: []
}
}
添加到它:
for(let b = 0; b < this.totalLength; b++){
this.$set(this.fetchList, b, {
id: b
})
};
您必须使用 this.$set
(或 Vue.set
),因为您要添加 dynamic indexes到数组。
这是一个演示:
new Vue({
el: "#app",
data: {
totalLength: '10',
fetchList: [],
},
methods: {
toggle: function(todo){
todo.done = !todo.done
},
grabTeams(){
for(let b = 0; b < this.totalLength; b++){
this.$set(this.fetchList, b, {
id: b
})
}
}
}
})
<div id="app">
<button @click="grabTeams()">
CLICK ME
</button>
{{ fetchList }}
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
关于javascript - Vue根据循环长度生成对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65260207/