Printing key in Vue.js iteration

2020-03-26 06:00发布

I have array like below

data() {
  return {
    shoppingItems: [
      {name: 'apple', price: '10'},
      {name: 'orange', price: '12'}
    ]
  }
}

I am trying to iterate like below

<ul>
  <li v-for="item in shoppingItems">
    {{ item.name }} - {{ item.price }}
  </li>
</ul>

I am getting output like below

  • apple - 10
  • orange - 12

But I would like to get output like below

  • name - apple, price - 10 //I would like to print key dynamically
  • name - orange, price - 12

标签: vue.js
3条回答
手持菜刀,她持情操
2楼-- · 2020-03-26 06:44

You can iterate over the keys/values with this :

<div v-for="(value, key) in object">
  {{ key }} - {{ value }}
</div>

You can also have the index of the current key :

<div v-for="(value, key, index) in object">
  {{ key }} - {{ value }}
  // if index > 0, add comma
</div>
查看更多
Juvenile、少年°
3楼-- · 2020-03-26 06:52

Object.Keys(Object) returns an array containing all the key of the object. Now you can use index to fetch the desire key -

<ul>
  <li v-for="item in shoppingItems">
    {{ Object.keys(item).indexOf(0) }} : {{ item.name }} - {{ Object.keys(item).indexOf(1) }} : {{ item.price }}
</li>
</ul>
查看更多
forever°为你锁心
4楼-- · 2020-03-26 06:53

You can use (key,value) pair in for loop

var app = new Vue({
  el:'#app',
  data() {
  return {
    shoppingItems: [
      {name: 'apple', price: '10'},
      {name: 'orange', price: '12'}
    ]
  }
}
});
li span{
  text-transform: capitalize;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<ul>
  <li v-for="item in shoppingItems">
    <span v-for="(v,i,count) in item">{{i}} - {{v}}<span v-show="count<(Object.keys(item).length-1)
">, </span></span>
  </li>
</ul>
</div>

查看更多
登录 后发表回答