[英]Iterate over object with count as value
在Vue應用程序中,我具有如下數據結構:
data: () => ({
currentKey: 1,
currentVal: 1,
obj: {
1: 3,
2: 4,
3: 2
}
}),
methods: {
stepForward() {
// this method should update currentKey and currentVal
}
}
還有一個帶有簡單按鈕的模板 ,用於遍歷對象。
<p>Key:{{ currentKey }} Value: {{ currentVal }}</p>
<v-btn @click="stepForward">Next</v-btn>
問題
單擊下一步按鈕,我想通過currentKey
迭代obj
的值來增加currentKey
和currentVal
的值。
預期結果
每單擊一次“下一步”按鈕,值將增加(直到到達最后一對),如下所示:
currentKey: 1
currentVal: 1
currentKey: 1
currentVal: 2
currentKey: 1
currentVal: 3
currentKey: 2
currentVal: 1
currentKey: 2
currentVal: 2
currentKey: 2
currentVal: 3
currentKey: 2
currentVal: 4
currentKey: 3
currentVal: 1
currentKey: 3
currentVal: 2
如何做到這一點?
謝謝你的幫助!
我建議更改您的對象結構,使其更加直觀。
我不熟悉vue如何跟蹤傳入的數據對象,但是這里有一個大概的想法:
if (currentVal === obj[currentKey]) {
currentVal = 1;
currentKey += 1;
} else {
currentVal += 1;
}
if (this.currentVal === this.obj[this.currentKey]) {
this.currentKey += 1;
this.currentVal = 1;
} else {
this.currentVal += 1;
}
將此代碼復制到stepForward方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.