Vue - 检查你是否在 v-for 循环的最后一个道具上

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

如果我有以下数据属性:

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

并想循环输出如下:

name: Joe, age: 35, department: IT

到目前为止我有:

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

但这显示:

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

末尾有一个额外的逗号,我如何让它检测到它是最后一个道具而不显示逗号?我认为 v-show 或 v-if 可能是解决方案,但不太清楚如何让它发挥作用。

这是一种方法。

<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>

您可以使用 computed 查看当前索引(v-if 的第三个参数)是否是最后一个 属性:

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

然后在你的 v-for:

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

这是 JSFiddle:https://jsfiddle.net/wv2ujxvn/

如果您想在代码中而不是在 Stack Overflow 上存储关于此模式的知识,您可以创建一个这样的组件:

<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>

这不一定会使代码变短,但更容易记住:

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

如果您循环遍历数组而不是对象,这里有一个解决方案:

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

这也有效:

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

您还可以通过在每个项目前插入逗号来“作弊”,因为它更容易检查 第一个 项目 (index !== 0)。

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

可惜Vue没有提供捷径

我个人比较喜欢用小的CSS:

<div class="list">
  <span>Item 1</span>
  <span>Item 2</span>
  <span>Item 3</span>
</div>
.list span:not(:last-child)::after {
  content: ',';
}