[英]Dynamically loop on keys of object
I have an object coming from upload 我有一个来自上传的对象
obj: {
name: 'Mike'
street: 'Love'
}
and I can loop through it via 我可以通过它遍历
<div v-for="test in obj">
<span>{{test.name}}, {{test.street}}</span>
</div>
and I get fine output. 我得到很好的输出。
However, the object keys became different depending on user upload, sometimes the key will become 但是,对象密钥根据用户上载而有所不同,有时密钥会变成
obj: {
address: 'street test 123',
fine: '32 PHP',
magic: 'Love'
}
How can I loop through it to become dynamic? 我如何遍历它才能变得动态起来?
you have to take all keys in one array then you can bind it. 您必须将所有键放在一个数组中,然后才能绑定它。
obj: {
address: 'street test 123',
fine: '32 PHP',
magic: 'Love'
}
var keys = Object.keys(obj);
<div>
<span>{{keys.join(,)}}</span>
</div>
You can just loop through the whole object like this, here index
is the variable name and item
is the value 您可以像这样遍历整个对象,这里的
index
是变量名,而item
是值
var app4 = new Vue({ el: '#app-4', data: { obj: { address: 'street test 123', fine: '32 PHP', magic: 'Love' } } })
<script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app-4"> <div v-for="(item, index) in obj"> <span>{{item}}</span> </div> </div>
I don't think you want to use v-for
for this purpose. 我认为您不想为此目的使用
v-for
。
This is what I would do without changing how you have your obj
set up: 这是我在不更改
obj
设置方式的情况下要做的事情:
<div id="foo">
{{computedVal}}
</div>
and in the Vue
instance, 在
Vue
实例中
new Vue({
data: {
// ... miscellaneous stuff
obj: {
prop1: 'val1',
prop2: 'val2',
prop3: 'val3',
}
},
methods:{ /* ... */ },
computed: {
computedVal(){
let str = '';
for(let key in this.obj){
let val = this.obj[key];
str += `<span>${key} : ${val}</span>`;
}
return str;
}
}
});
This will be your output: 这将是您的输出:
<div id="foo">
<span>prop1 : val1</span>
<span>prop2 : val2</span>
<span>prop3 : val3</span>
</div>
Of course you can do this inside v-for
as well. 当然,您也可以在
v-for
执行此操作。
My understanding is that as of now, Vue doesn't do object property iteration inside v-for
. 我的理解是,到目前为止,Vue不在
v-for
内进行对象属性迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.