ElementUI中使用el-calendar实现基于日历的节假日的增删改查

生活中,最使人疲惫的往往不是道路的遥远,而是心中的郁闷;最使人痛苦的往往不是生活的不幸,而是希望的破灭;最使人颓废的往往不是前途的坎坷,而是自信的丧失;最使人绝望的往往不是挫折的打击,而是心灵的死亡。所以我们要有自己的梦想,让梦想的星光指引着我们走出落漠,走出惆怅,带着我们走进自己的理想。

导读:本篇文章讲解 ElementUI中使用el-calendar实现基于日历的节假日的增删改查,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

场景

前端使用ElementUI的el-calendar组件实现可视化的节假日的增删改查。

主页面显示效果如下

 

ElementUI中使用el-calendar实现基于日历的节假日的增删改查

点击日历组件上的某天进行新增节假日时

 

ElementUI中使用el-calendar实现基于日历的节假日的增删改查

点击已经存在的节假日编辑时

 

ElementUI中使用el-calendar实现基于日历的节假日的增删改查

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

首先el-calendar是支持自定义内容的,官方文档地址:

https://element.eleme.cn/#/zh-CN/component/calendar

官方示例文档:

通过设置名为 dateCell 的 scoped-slot 来自定义日历单元格中显示的内容。在 scoped-slot 可以获取到 date(当前单元格的日期), data(包括 type,isSelected,day 属性)。详情解释参考下方的 API 文档。

ElementUI中使用el-calendar实现基于日历的节假日的增删改查

 

官方示例代码

<el-calendar>
  <!-- 这里使用的是 2.5 slot 语法,对于新项目请使用 2.6 slot 语法-->
  <template
    slot="dateCell"
    slot-scope="{date, data}">
    <p :class="data.isSelected ? 'is-selected' : ''">
      {{ data.day.split('-').slice(1).join('-') }} {{ data.isSelected ? '✔️' : ''}}
    </p>
  </template>
</el-calendar>
<style>
  .is-selected {
    color: #1989FA;
  }
</style>

仿照官方代码,这里新增一个自定义内容的el-calendar

      <template
        slot="dateCell"
        slot-scope="{date, data}">
        <p :class="rqi.indexOf(data.day) > -1 ? 'is-selected' : ''" @click="handleBianJi(data.day)">
          {{ data.day.split('-').slice(1).join('-') }} {{ rqi.indexOf(data.day) > -1 ? rqineirong[data.day].jqmc : ''}}
        </p>
      </template>
    </el-calendar>

注意:

1.为了首先已经设置过节假日的日期颜色为绿色,所以这里绑定class使用的是选择表达式

rqi.indexOf(data.day) > -1 ? 'is-selected' : ''"

其中rei是一个用来查询所有的假期的索引数组,索引值为获取的日期

 

ElementUI中使用el-calendar实现基于日历的节假日的增删改查

通过判断当前日期是否在假期的索引数组中来绑定is-selected样式。

所以需要提前声明数组rqi

  data() {
    return {
      rqi:[],

以及定义样式is-selected

<style lang="scss" scoped>
  .is-selected {
    color: white;
    background: green;
  }
</style>

2.然后绑定了单击事件

@click="handleBianJi(data.day)"

用于对新增和编辑假期的触发。

3.具体显示的内容模板通过

{{ data.day.split('-').slice(1).join('-') }} {{ rqi.indexOf(data.day) > -1 ? rqineirong[data.day].jqmc : ''}}

根据文档,通过data.day获取的日期格式为yyyy-MM-dd,这里只取月和日,然后后面是选择表达式,

如果当前日期的索引存在,则在后面加上假期的名称。

其中rqineirong是一个键值对的对象,键是节假日中的日期,值是所属节假日的相关信息。

所以需要提前声明此对象。

  data() {
    return {
      rqi:[],
      rqineirong:{},

然后就是在页面刚加载完之后查询出所有的假期并构造出这种前端所需要的键值对对象的格式。

  created() {
    this.getList();
  },

在查询所有假期的请求数据的方法中

  methods: {
    /** 查询节假日管理 - 法定节假日列表 */
    getList() {
      this.loading = true;
      listFdjjr(this.queryParams).then(response => {
        this.rqi = [];
        this.rqineirong = {};
        for(let i=0;i<response.length;i++){
          for(var key in response[i]){
            this.rqi.push(key)
            this.rqineirong[key] = response[i][key]
          }
        }
      });
    },

其中调用请求后台数据的方法,将后台数据构造成索引的数组和一个键值对的对象。

ElementUI中使用el-calendar实现基于日历的节假日的增删改查

请求后台数据的js方法

// 查询节假日管理 - 法定节假日列表
export function listFdjjr(query) {
  return request({
    url: 'jjrgl/fdjjr/fdjjrList',
    method: 'get',
    params: query
  })
}

就是向后台发送get请求,来到后台数据部分。

首先需要设计数据库

 

ElementUI中使用el-calendar实现基于日历的节假日的增删改查

使用代码生成工具生成后台代码,来到Controller层

    @GetMapping("/fdjjrList")
    public List<Map<String, Object>> fdjjrList() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //保存日期集合
        List<String> dateList = new ArrayList<String>();
        List<Fdjjr> list = fdjjrService.selectFdjjrList(null);
        for (int i = 0; i < list.size(); i++) {
            Fdjjr fdjjr = list.get(i);
            Date date_start = fdjjr.getKssj();
            Date date_end = fdjjr.getJssj();
            Date date = date_start;
            //用Calendar 进行日期比较判断
            Calendar cd = Calendar.getInstance();
            while (date.getTime() <= date_end.getTime()) {
                cd.setTime(date);
                Map<String, Object> map = new HashMap<>();
                map.put(sdf.format(date), fdjjr);
                resultList.add(map);
                //增加一天 放入集合
                cd.add(Calendar.DATE, 1);
                date = cd.getTime();
            }
        }
        return resultList;
    }

最终后台构造成的数据结构为

 

ElementUI中使用el-calendar实现基于日历的节假日的增删改查

最终要将数据库中每个节假日的开始到结束日期每一天构造成一个键值对,键是日期,值是日期所属的假期对象。

这样就完成了 已有节假日的显示,若要再实现点击某天进行新增或者编辑节假日,上面已经添加了点击事件

@click="handleBianJi(data.day)"

在点击事件里

    /** 编辑日期操作 */
    handleBianJi(day) {
      if(this.rqineirong[day]){
        console.log(this.rqineirong[day])
        this.form = this.rqineirong[day];
        this.title = '编辑节假日';
      }else{
        let obj = {};
        obj.kssj = day.valueOf();
        obj.jssj = day.valueOf();
        this.form = obj;
        this.form = obj;
        this.title = '新增节假日';
      }
      this.open = true;
    },

进行打开新增或者编辑页面的操作,判断条件是

if(this.rqineirong[day])

前面已经在页面初始化后将查询结果查询并存放在this.rqineirong里面,在点击事件中获取当前日期,并判断是否是节假日,如果是则显示编辑,否则显示新增

新增和编辑页面的代码

    <!-- 添加或修改节假日管理 - 法定节假日对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="假期名称" prop="jqmc">
          <el-input v-model="form.jqmc" placeholder="请输入假期名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="kssj">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.kssj"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="jssj">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.jssj"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型" prop="lx">
          <el-select v-model="form.lx" placeholder="请选择类型" clearable :style="{ width: '200px' }">
            <el-option
              v-for="dict in jjrlxOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="title == '编辑节假日'" @click="deleteForm" :style="{ background: 'red',color:'white'}">删除</el-button>
      </div>
    </el-dialog>

如果是编辑的话会将对应的日期key获取到的节假日的内容赋值给this.form,并已经与显示的控件进行双向绑定。

相应的对节假日进行编辑和删除只要调用接口实现即可。

index.vue完整代码

<template>
  <div class="app-container">
    <el-calendar>
      <template
        slot="dateCell"
        slot-scope="{date, data}">
        <p :class="rqi.indexOf(data.day) > -1 ? 'is-selected' : ''" @click="handleBianJi(data.day)">
          {{ data.day.split('-').slice(1).join('-') }} {{ rqi.indexOf(data.day) > -1 ? rqineirong[data.day].jqmc : ''}}
        </p>
      </template>
    </el-calendar>

    <!-- 添加或修改节假日管理 - 法定节假日对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="假期名称" prop="jqmc">
          <el-input v-model="form.jqmc" placeholder="请输入假期名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="kssj">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.kssj"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="jssj">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.jssj"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型" prop="lx">
          <el-select v-model="form.lx" placeholder="请选择类型" clearable :style="{ width: '200px' }">
            <el-option
              v-for="dict in jjrlxOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="title == '编辑节假日'" @click="deleteForm" :style="{ background: 'red',color:'white'}">删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFdjjr, delFdjjr, addFdjjr, updateFdjjr } from "@/api/jjrgl/fdjjr";

export default {
  jqmc: "Fdjjr",
  data() {
    return {
      rqi:[],
      rqineirong:{},
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jqmc: [
          { required: true, message: "假期名称不能为空", trigger: "blur" }
        ],
        kssj: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        jssj: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        lx: [
          { required: true, message: "假期类型不能为空", trigger: "change" }
        ],
      },
      // 节假日类型
      jjrlxOptions: [],
    };
  },
  created() {
    this.getList();
    this.getDicts("jjr_fdjjr_lx").then(response => {
      this.jjrlxOptions = response.data;
    });
  },
  methods: {
    /** 查询节假日管理 - 法定节假日列表 */
    getList() {
      this.loading = true;
      listFdjjr(this.queryParams).then(response => {
        this.rqi = [];
        this.rqineirong = {};
        for(let i=0;i<response.length;i++){
          for(var key in response[i]){
            this.rqi.push(key)
            this.rqineirong[key] = response[i][key]
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jqmc: undefined,
        kssj: undefined,
        jssj: undefined,
        lx: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery(day) {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateFdjjr(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.reset();
                this.getList();
              }
            });
          } else {
            addFdjjr(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.reset();
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 编辑日期操作 */
    handleBianJi(day) {
      if(this.rqineirong[day]){
        console.log(this.rqineirong[day])
        this.form = this.rqineirong[day];
        this.title = '编辑节假日';
      }else{
        let obj = {};
        obj.kssj = day.valueOf();
        obj.jssj = day.valueOf();
        this.form = obj;
        this.form = obj;
        this.title = '新增节假日';
      }
      this.open = true;
    },
    deleteForm(){
      let ids = [];
      ids.push(this.form.id)
      delFdjjr(ids).then(response => {
        if (response.code === 200) {
          this.msgSuccess("删除成功");
          this.open = false;
          this.reset();
          this.getList();
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
  .is-selected {
    color: white;
    background: green;
  }
</style>

调用接口的js完整代码

import request from '@/utils/request'

// 查询节假日管理 - 法定节假日列表
export function listFdjjr(query) {
  return request({
    url: 'jjrgl/fdjjr/fdjjrList',
    method: 'get',
    params: query
  })
}


// 新增节假日管理 - 法定节假日
export function addFdjjr(data) {
  return request({
    url: '/jjrgl/fdjjr',
    method: 'post',
    data: data
  })
}

// 修改节假日管理 - 法定节假日
export function updateFdjjr(data) {
  return request({
    url: '/jjrgl/fdjjr',
    method: 'put',
    data: data
  })
}

// 删除节假日管理 - 法定节假日
export function delFdjjr(id) {
  return request({
    url: '/jjrgl/fdjjr/' + id,
    method: 'delete'
  })
}

后台Controller完整代码

@RestController
@RequestMapping("/jjrgl/fdjjr")
@Api(tags = "节假日管理")
public class FdjjrController extends BaseController {
    @Autowired
    private IFdjjrService fdjjrService;


    /**
     * 新增节假日管理 - 法定节假日
     */
    @ApiOperation("法定节假日新增")
    @PreAuthorize("@ss.hasPermi('jjrgl:fdjjr:add')")
    @Log(title = "节假日管理 - 法定节假日", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Fdjjr fdjjr) {
        return toAjax(fdjjrService.insertFdjjr(fdjjr));
    }


    /**
     * 删除节假日管理 - 法定节假日
     */
    @PreAuthorize("@ss.hasPermi('jjrgl:fdjjr:remove')")
    @Log(title = "节假日管理 - 法定节假日", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除法定节假日")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fdjjrService.deleteFdjjrByIds(ids));
    }

    @ApiOperation("法定节假日列表-日历")
    @GetMapping("/fdjjrList")
    public List<Map<String, Object>> fdjjrList() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //保存日期集合
        List<String> dateList = new ArrayList<String>();
        List<Fdjjr> list = fdjjrService.selectFdjjrList(null);
        for (int i = 0; i < list.size(); i++) {
            Fdjjr fdjjr = list.get(i);
            Date date_start = fdjjr.getKssj();
            Date date_end = fdjjr.getJssj();
            Date date = date_start;
            //用Calendar 进行日期比较判断
            Calendar cd = Calendar.getInstance();
            while (date.getTime() <= date_end.getTime()) {
                cd.setTime(date);
                Map<String, Object> map = new HashMap<>();
                map.put(sdf.format(date), fdjjr);
                resultList.add(map);
                //增加一天 放入集合
                cd.add(Calendar.DATE, 1);
                date = cd.getTime();
            }
        }
        return resultList;
    }
    @ApiOperation("法定节假日列表-下拉")
    @GetMapping("/typeList")
    public List<Fdjjr> typeList() {
        List<Fdjjr> list = fdjjrService.selectFdjjrList(null);
        return list;
    }


    /**
     * 修改节假日管理 - 法定节假日
     */
    @PreAuthorize("@ss.hasPermi('jjrgl:fdjjr:edit')")
    @Log(title = "节假日管理 - 法定节假日", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Fdjjr fdjjr) {
        return toAjax(fdjjrService.updateFdjjr(fdjjr));
    }

}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/136512.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!