Vue - check if you are on the last prop of a v-for loop

笑着哭i 提交于 2020-07-14 23:47:57

问题


If I have the following data property:

person: {name: 'Joe', age: 35, department: 'IT'}

And wanted to loop through and output it as follows:

name: Joe, age: 35, department: IT

So far I have:

<span v-for="(val, key) in person">{{key}}: {{val}}, </span>

But this displays:

name: Joe, age: 35, department: IT,

with an extra comma on the end, how can I have it detect that it's the last prop and not show the comma? I thoughta v-show or v-if may be the solution but can't quite figure out how to make it work.


回答1:


Here is one way.

<span v-for="(val,key,index) of person">
  key: {{key}}, val: {{val}}, index: {{index}}
  <span v-if="index != Object.keys(person).length - 1">, </span>
</span>



回答2:


Works Great

<div id="app">
  <div v-for="(item, index) in items">
    <div v-if="index == items.length - 1">yes</div>
    {{ item }}, {{ index }}
  </div>
</div>



回答3:


You can do that with a computed to see if the current index (third parameter forv-if) is the last property:

computed: {
  last(){
     return Object.keys(this.person).length-1;
  }
}

Then in your v-for:

<span v-for="(val, key, index) in person">{{key}}: {{val}}<span v-if="index !== last">, </span> </span>

Here's the JSFiddle: https://jsfiddle.net/wv2ujxvn/




回答4:


You can also "cheat" by inserting the comma before each item, as it's easier to check for the first item (key !== 0).

<span v-for="(val, key) in person">
  <span v-if="key !== 0">, </span>
  {{key}}: {{val}}
</span>



回答5:


This also works .

<span v-for="(value,key) in persons" :key='key'>
    {{key}}: {{val}} 
    <span v-if="key+1 != persons.length">, </span>
</span>




回答6:


If you want to store the knowledge about this pattern in code instead of on Stack Overflow, you could create a component like this:

<template>
  <span v-if="show"><slot></slot></span>
</template>
<script>
  export default {
    name: 'separator',
    props: ['items', 'index'],
    computed: {
      show () {
        return this.index !== (Array.isArray(this.items) ? this.items : Object.keys(this.items)).length - 1
      }
    }
  }
</script>

This doesn't necessarily make the code shorted, but easier to remember:

<span v-for="(val, key, index) of person">key: {{key}}, val: {{val}}<separator :items="person" :index="index">, </separator></span>


来源:https://stackoverflow.com/questions/42740105/vue-check-if-you-are-on-the-last-prop-of-a-v-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!