创建一种轮播 Vue

Create kind of carousel Vue

所以,我有一个仪表板,我想在其中显示一些卡片。一次应该只有四个可见,当单击箭头时,您只想移动一个步骤到下一张卡片。所以假设卡片 1-4 正在显示,当单击向右箭头时,您应该能够看到 2-5。现在我只有当你点击右箭头时,你会跳过 1-4 并直接进入 5-10。

所以现在我有这个:

computed: {
    cardsToDisplay(): Status[] {
        return this.cards.slice(this.page * 4, (this.page + 1) * 4)
    },
},
methods: {
    setCards(no: number) {
        this.page = this.page + delta
    },
},

在模板中,左右箭头按钮如下所示:

        <v-icon v-if="page !==" class="black--text font-weight-bold" 
          @click="setPage(-1)">
          chevron_left</v-icon>

        <v-icon
            v-if="columns.length > (page + 1) * 4"
            class="black--text font-weight-bold"
            @click="setPage(1)"
            >chevron_right</v-icon
        >

但是我怎样才能让它移动到下一张卡片呢? :)

随心所欲

computed: {
    cardsToDisplay(): Status[] {
        return [...this.cards, ...this.cards].slice(this.cards_pos, this.cards_pos + 4)
    },
},
methods: {
    prev() {
        this.cards_pos = (this.cards_pos + this.cards.length - 1) % this.cards.length;
    },
    next() {
        this.cards_pos = (this.cards_pos + 1) % this.cards.length;
    },
},

使用 [...this.cards, ...this.cards] 无需太多代码即可确保轮播是循环的。
使用余数运算符,您可以确保 card_pos 始终小于卡片数量。随着递减,您需要添加数组长度,以防止进入负数。

Vue.createApp({
  data: () => ({
    cards_pos: 0,
    cards: new Array(10).fill(null).map((e, i) => ({
      img: "https://picsum.photos/id/" + (i * 10) + "/200",
      text: "Card #" + (i + 1)
    }))
  }),
  computed: {
    cardsToDisplay() {
      return [...this.cards, ...this.cards].slice(this.cards_pos, this.cards_pos + 4)
    },
  },
  methods: {
    prev() {
      this.cards_pos = (this.cards_pos + this.cards.length - 1) % this.cards.length;
    },
    next() {
      this.cards_pos = (this.cards_pos + 1) % this.cards.length;
    },
  },
}).mount("#app")
.cards {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}

.cards > * {
  width: 25%;
}

.cards > * img {
  width: 100%;
}
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <button @click="prev">
    &lt;&lt;
  </button>
  <button @click="next">
    &gt;&gt;
  </button>
  <ol class="cards">
    <li v-for="card in cardsToDisplay">
      <img :src="card.img" />
      <p>
        {{ card.text }}
      </p>
    </li>
  </ol>
</div>