element中el-date-picker的禁用日期小技巧

6,606 阅读1分钟

需求分析:el-date-picker需要根据后台传递的值来设置禁用日期。

例如:后台传递2019-07-02,用户就只能选择2019-07-02之后的时间。具体代码如下

<el-table-column label="日期">
  <template v-slot="scope">
    <el-date-picker
      v-model="scope.row.date"
      type="date"
      placeholder="选择日期"
    ></el-date-picker>
  </template>
</el-table-column>

难点分析

查看官网例子,发现disabledDate可以设置禁用日期。

pickerOptions: {
  disabledDate(time) {
    return time.getTime() < Date.now();
  }
}
<el-table-column label="日期">
  <template v-slot="scope">
    <el-date-picker
      v-model="scope.row.date"
      type="date"
      placeholder="选择日期"
      :picker-options="pickerOptions"
    ></el-date-picker>
  </template>
</el-table-column>

难点就在怎么把return time.getTime() < Date.now();这句中的Date.now()换成后台传递过来的初始值。

解决思路

整体思路如下:
1、后台返回值后,深拷贝一份存在一个数组中oldTableList
2、日期选择框获取焦点的时候,获取下标index,将这个下标存在一个初始值里selectIndex。 3、通过oldTableList[selectIndex].date,获取到初始日期。
整体代码如下:

import axios from "axios";
import _ from "lodash";
export default {
  data() {
    return {
      tableList: [],
      oldTableList: [],
      selectIndex: null,
      pickerOptions: {}
    };
  },
  created() {
    var $this = this;
    $this.init();
    $this.pickerOptions = {
      disabledDate(time) {
        return time.getTime() <new Date($this.oldTableList[$this.selectIndex].date).getTime();
      }
    };
  },
  methods: {
    init() {
      // 这个地址是我mock的地址,任何人都可以访问(https://www.easy-mock.com/mock/5d0a0470db605746a1228700/test/test)
      axios.get("https://www.easy-mock.com/mock/5d0a0470db605746a1228700/test/test").then(({ data }) => {
        /**
         * 这里用了lodash的深拷贝
         * 注意:必须要深拷贝这个对象数组,不然改tableList同时oldTableList也会被改变。
         * 要保证oldTableList是最初的数据
         *
         */
        this.tableList = _.cloneDeep(data.data);
        this.oldTableList = _.cloneDeep(data.data);
      });
    },
    handleDateFocus(index) {
      this.selectIndex = index;
    }
  }
};

template代码如下

<div>
  <el-table :data="tableList">
    <el-table-column label="姓名" prop="name"></el-table-column>
    <el-table-column label="日期">
      <template v-slot="scope">
        <el-date-picker
          v-model="scope.row.date"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions"
          @focus="handleDateFocus(scope.$index)"
        ></el-date-picker>
      </template>
    </el-table-column>
  </el-table>
</div>

说明

这个问题我网上搜了半天也没搜到解决方法,以上方法是我自己想出来的,如果你有更好的方法,欢迎留言讨论