快速简单的实现在日历上签到的功能,不需要日历组件,带后端实现讲解

2020-07-08  本文已影响0人  王乐城愚人云端

原本想使用日历组件,发现太麻烦,仅仅就签到而已,把当月的日期渲染一下就可以了,样式也可以自己随便写,用日历组件还得想办法改日历组件的样式。

以下使用到了vue,vant就用了弹窗、按钮,换成其他的也行。


image.png

前端

<template>
  <div>
    <van-dialog
      use-slot
      :title="month + '月签到'"
      :show="show"
      closeOnClickOverlay
      :showConfirmButton="false"
      @close="onClose"
    >
      <div class="sign-in-wrap">
        <ul>
          <li v-for="item in signInDays" :key="item.day">
            <div :class="{active: item.isToday}">{{item.day}}</div>
            <van-icon color="#e41f19" name="success" v-if="item.signIn"/>
            <div v-if="!item.signIn && item.isToday" class="today">今天</div>
          </li>
        </ul>
        <div style="padding: 10px">
          <van-button round block color="#e41f19" :disabled="isSignInToady" @click="signIn">{{ isSignInToady ? '今日已签到' : '签到'}}</van-button>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
export default {
  name: 'index',
  data() {
    return {
      show: false,
      isSignInToady: false,
      signInCount: 0,
      signInMap: [],
      month: 0,
      signInDays: [], // [{day: 1, signIn: false, active: false, today: false}]
    }
  },
  methods: {
    // 点击签到
    signIn() {
      if (!this.isSignInToady) {
        this.$api.signIn().then((res) => {
          this.signInMap[new Date().getDate()] = true
          this.signInCount = this.signInCount + 1
          this.isSignInToady = true
          wx.showToast({ icon: 'success', title: '签到成功' })
          this.$store.dispatch('getUserDetail')
          this.renderSignInDays()
        })
      }
    },
    // 渲染本月日期
    renderSignInDays() {
      const now = new Date()
      const nowDate = now.getDate()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      this.month = month
      const day = new Date(year, month, 0)
      const days = day.getDate()
      const signInDays = []
      for (let i = 0; i < days; i++) {
        signInDays.push({
          day: i + 1,
          signIn: this.signInMap[i + 1],
          isToday: nowDate - 1 === i,
        })
        if (nowDate - 1 === i && this.signInMap[i + 1]) {
          this.isSignInToady = true
        }
      }
      this.signInDays = signInDays
    },
    // 显示签到框
    showSignIn() {
      this.show = true
      this.renderSignInDays()
    },
    getDate() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const d = new Date(year, month, 0)
      return d.getDate()
    },
    onClose() {
      this.show = false
    },
    // 获取本月的签到记录
    getThisMonthSignInRecord() {
      this.$api.getMonthSignInRecord().then(({ value: res }) => {
        this.signInCount = res.length
        const day = new Date().getDate()
        res.forEach((item) => {
          this.signInMap[item.day] = true
          if (day === item.day) {
            this.isSignInToady = true
          }
        })
      })
    },
  },
  mounted() {
      this.getThisMonthSignInRecord()
  },
}
</script>

<style scoped lang="scss">
  @import "../../assets/css/varible";
  .sign-in-wrap{
    padding: 20px 0;
    ul{
      display: flex;
      flex-wrap: wrap;
      li{
        width: 14%;
        text-align: center;
        height: 40px;
        .today{
          font-size: 10px;
          color:$text-light;
        }
        color: $text-light;
        .active{
          color: $text;
          font-weight: bold;
        }
      }
    }
  }
</style>

后端

数据表

create table sign_in (
    id int auto_increment primary key,
    user_id int null,
    created_at datetime default CURRENT_TIMESTAMP null,
    month int not null comment '月份格式:202001',
    day int not null comment '日期 1 - 31'
) comment '用户签到' charset = utf8;

java spring

@ApiOperation(value = "用户每日签到")
@PostMapping("/signIn")
public BaseResp signIn() {
    return treasureService.getSignIn();
}


@ApiOperation(value = "查询今日是否签到")
@GetMapping("/isSignIn")
public ResultData<Boolean> isSignIn(Principal principal) {
    return treasureService.isSignIn(principal.getName());
}

@ApiOperation(value = "获取当月签到记录")
@GetMapping("/getMonthSignInRecord")
public ResultData<List<SignIn>> getMonthSignInRecord() {
    return treasureService.getMonthSignInRecord();
}

实现 service


    @Override
    public BaseResp getSignIn() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Integer month = Integer.valueOf(sdf.format(now));
        sdf = new SimpleDateFormat("d");
        Integer day = Integer.valueOf(sdf.format(now));
        System.out.println(month);
        System.out.println(day);
        SignIn result = signInDAO.findOneByUserIdAndMonthAndDay(user.getId(), month, day);
        if (result == null) {
            // 签到
            signInDAO.insert(SignIn.builder()
                    .userId(user.getId())
                    .createdAt(now)
                    .month(month)
                    .day(day)
                    .build());

            // 加经验
            String signInExp = webConfigDAO.getValueByName(WebConfigEnum.SIGN_IN.getConfig());
            SignInExpDTO signInExpDTO = JSON.parseObject(signInExp, SignInExpDTO.class);
            Integer exp = signInExpDTO.getOne();

            Integer count = signInDAO.countByUserIdAndMonth(user.getId(), month);
            if (count == 10) {
                exp = exp + signInExpDTO.getTen();
            } else if (count == 20) {
                exp = exp + signInExpDTO.getTwenty();
            }

            Integer sum = user.getExp() + exp;
            user.setExp(sum);
            user.setLevel(countLevelByExp(sum));
            userDAO.updateUserExpAndLevel(user);

            return new BaseResp();
        } else {
            return new BaseResp(ResultCode.SIGN_IN_TODAY);
        }
    }

    @Override
    public ResultData<Boolean> isSignIn(String username) {
        User user = userDAO.selectByUsername(username);
        Integer result = signInDAO.countTodaySignIn(user.getId());
        ResultData<Boolean> resultData = new ResultData<>();
        resultData.setValue(result > 0);
        return resultData;
    }

    @Override
    public ResultData<List<SignIn>> getMonthSignInRecord() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Integer month = Integer.valueOf(sdf.format(now));
        return new ResultData<>(signInDAO.findAllByUserIdAndMonth(user.getId(), month));
    }

上一篇下一篇

猜你喜欢

热点阅读