首页 > 解决方案 > 我想使用 Javascript/Vue 将当前周作为日期数组返回

问题描述

我正在尝试返回一组日期。类似于下面的。

我想有一个以天为单位的 1 周周期数组,一次分页 7 天,带有“下周”和“上一周”按钮。

理想情况下,我希望它是纯 JavaScript

选择芯片

标签: javascriptvue.js

解决方案


在此示例中使用计算属性很重要,因为您可以更改周(下周或之前)。

尝试这样的事情:

<template>
  <div>
    <div>
      <button @click="priorWeek">Prior Week</button>
      <span v-for="day in days" class="day">
        {{ day.toLocaleDateString() }}
      </span>
      <button @click="nextWeek">Next Week</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data: () => ({
    first: new Date(),
  }),
  computed: {
    days() {
      return [
        this.first,
        this.addDays(this.first, 1),
        this.addDays(this.first, 2),
        this.addDays(this.first, 3),
        this.addDays(this.first, 4),
        this.addDays(this.first, 5),
        this.addDays(this.first, 6),
      ];
    },
  },
  methods: {
    addDays(date, days) {
      let newDate = new Date(date);
      newDate.setDate(this.first.getDate() + days);
      return newDate;
    },
    subtractDays(date, days) {
      let newDate = new Date(date);
      newDate.setDate(this.first.getDate() - days);
      return newDate;
    },
    nextWeek() {
      this.first = this.addDays(this.first, 7);
    },
    priorWeek() {
      this.first = this.subtractDays(this.first, 7);
    },
  },
};
</script>

<style>
.day {
  background-color: rgb(240, 240, 240);
  border-radius: 1rem;
  color: purple;
  display: inline-block;
  margin-left: 0.5rem;
  padding: 0.5rem;
}
</style>

推荐阅读