我有一个 Teams 对象,它记录了所有
团队,还可以计数
和创建
团队。我将所有团队存储为一个对象,因此可以编写 Teams.all["Team 1"]
来选择名称为“Team 1”的团队。
Teams.js
var Teams = {
all: {},
create: function(teamName) {
var key = 'Team ' + this.count();
this.all[key] = {
'name': teamName,
'score': 0
};
},
count: function() {
var total = 0;
for(var team in this.all){
if(this.all.hasOwnProperty(team)){
total ++;
}
}
return total;
}
}
现在在 vue 中我想循环遍历这个。
main.js
var vueApp = new Vue({
el: '#app',
data: {
'Teams' : Teams
},
methods : {
createTeam : function(){
Teams.create('Team ' + (Teams.count() + 1));
}
}
});
然后这不起作用(显然):
index.html
<div id="app">
<ul>
<li v-for="team in Teams.all">{{ team.name }}</li>
</ul>
<button @click="createTeam">Create team</button>
</div>
所以我的下一个猜测是这样的:
index.html
<div id="app">
<ul>
<li v-for="team in Teams.all">{{ Teams.all[team].name }}</li>
</ul>
<button @click="createTeam">Create team</button>
</div>
但这也行不通。有没有办法在Vue中循环访问对象的属性?
最佳答案
您的 Teams 状态不是 react 性的,因为您正在向其中添加对象键...请在此处阅读此文档:http://rc.vuejs.org/guide/reactivity.html#Change-Detection-Caveats .
使用this.$set(this.someObject, 'b', 2)
如果您想向状态对象添加属性,或者这些属性不会 react 并触发 View 更新。
也不知道为什么你把事情搞得这么复杂:)。试试这个:
var vueApp = new Vue({
el: '#app',
data: {
teams: []
},
methods: {
addTeam: function() {
this.teams.push({
name: 'Team ' + this.teams.length,
score: 0
})
}
}
});
<小时/>
<div id="app">
<ul>
<li v-for="team in teams">
{{ team.name }}
</li>
</ul>
<button @click="addTeam">Create team</button>
</div>
关于javascript - v-for 通过 vue.js 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39836504/