vue 3.2 table 简易日历组件

<template>
  <table>
    <thead>
      <th v-for="(item, index) in title" :key="index">
        {{ item }}
      </th>
    </thead>
    <tbody>
      <tr v-for="(item, index) in trData" :key="index">
        <td
          v-for="(num, key) in item"
          :key="key"
          @click="clickMonth(num)"
          :class="{ active: choosedData.includes(num) }"
        >
          {{ num }}
        </td>
      </tr>
    </tbody>
  </table>
</template>
<script>
export default defineComponent({
  name: 'SCalendar',
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    days: {
      type: Number,
      default: 31
    },
    groupNum: {
      type: Number,
      default: 7
    },
    title: {
      type: Array,
      default: () => ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
    }
  },
  setup(props, { emit }) {
    const { days, groupNum, modelValue } = props
    const trData = ref([])
    const choosedData = computed({
      get: () => modelValue,
      set: (val) => {
        emit('update:modelValue', val)
      }
    })
    function init() {
      const list = Array.from({ length: days + 1 }, (_, i) => i)
      let groups = []
      for (let i = 1; i <= list.length; i += groupNum) {
        const group = list.slice(i, i + groupNum)
        groups.push(group)
      }
      trData.value = groups
    }
    function clickMonth(val) {
      const data = choosedData.value
      if (data.includes(val)) {
        const index = data.findIndex((g) => g === val)
        data.splice(index, 1)
      } else {
        data.push(val)
      }
    }
    init()
    return { trData, choosedData, clickMonth }
  }
})
</script>
<style scoped>
table {
  border-collapse: collapse;
  text-align: center;
}
th,
td {
  border: 1px solid #d9d9d9;
}

td {
  width: 50px;
  height: 50px;
  cursor: pointer;
}
.active {
  background-color: #1890ff;
  color: #fff;
}
</style>

 <SCalendar v-model="list" />

vue 3.2 table 简易日历组件_第1张图片

你可能感兴趣的:(vue.js,javascript,ecmascript)