需求:每行三个盒子,前两个盒子右边有竖线,最后一个不显示竖线
看到这个需求的时候,我想到了css的:last-child选择器,last-child选择器究竟能不能达到我们的需求呢?我用vue+element-ui专门为本文做了一个demo,给大家演示效果
第一种方法:last-child选择器
在使用:last-child选择器的时候遇到不起作用的问题,具体的点击链接查看:last-child选择器不起作用
:last-child 选择器匹配属于其父元素的最后一个子元素的每个元素。

image.png
html部分:
<template>
<el-card shadow="never">
      <div>
        <el-row :gutter="20">
          <el-col :span="8" class="line">
            <p>第一个盒子</p>
          </el-col>
          <el-col :span="8" class="line"> <p>第二个盒子</p></el-col>
          <el-col :span="8" class="line"> <p>第三个盒子</p></el-col>
        </el-row>
      </div>
</el-card>
</template>
css部分:
<style lang="scss" scoped>
.line:last-child {
  border: 0;
}
.line {
  border-right: 1px solid #ccc;
}
</style>
:last-child选择器去掉一行盒子的最后一个貌似能行得通,但我的需求有两行盒子,去掉每一行的最后一个竖线,这个方法就不灵┭┮﹏┭┮

image.png
看来我们需要想其他方法了,于是在网上查了一下,有了更好的解决方法
v-bind:calss+计算
这里涉及到一个小小的计算,在这里和大家说下,不懂没关系,遇到这样的需求会用就行(▽)
(index + 1) % 3 == 0,这里的index的值为2(第三项),5(第六项),
8(第九项)......以此类推我们会发现,我们发现最后一项都是3的倍数,这些值里,(index+1)%3 ==0为每行最后一个元素,需要显示竖线。这里的index是数组里面的下标,所以index+1表示当前数组里面的第几项,然后(index+1)%3,每满3,顺序数除以3余数都为0。

image.png
html部分:
<template>
<el-card shadow="never">
      <div>
        <el-row :gutter="20">
          <el-col
            :span="8"
            :class="{ line: (index + 1) % 3 != 0 }"
            style="margin:15px 0px;"
            v-for="(item, index) in list"
            :key="index"
          >
            <p>{{ item.key }}</p>
          </el-col>
        </el-row>
      </div>
</el-card>
</template>
js部分:
<script>
data() {
    return {
       list: [
        { key: "第一个盒子" },
        { key: "第一个盒子" },
        { key: "第一个盒子" },
        { key: "第一个盒子" },
        { key: "第一个盒子" },
        { key: "第一个盒子" }
      ]
    }
  }
</script>
css部分:
<style lang="scss" scoped>
.line {
  border-right: 1px solid #ccc;
}
</style>

image.png
到目前为止,我们想要的需求就实现完成啦