avue常用場景記錄 《ASP.NET MVC企業級實戰》

  接手的一個項目使用的是avue這個傻瓜式的專門給後端人員用的框架,文檔不夠友好,使用起來各種蛋疼(咱專業前端基本上不使用)。爲此,專門記錄一下。當前avue版本2.8.12,如果要切換avue的版本,可以去https://cdn.jsdelivr.net/npm/@smallwei/[email protected]/lib/這個地址去選擇自己要的版本,然後進行下載,我這裏是通過cdn的方式引用的。

  avue官網地址:https://www.avuejs.com/

彈窗表單級聯

先選擇來源系統,根據所選擇的來源系統,自動加載來源表,如下圖所示:

js代碼如下:

 {
            label: this.$t("sourceDatasource"),
            prop: "sourceDatasource",
            type: "select",
            clearable: false,
            dicData: [],
            cascaderItem: ["sourceTable"],
            // dicUrl: `/emptech-middle/dataSource/list`,
            // dicQuery: { current: 1, size: 100 , descs: "create_time",dsType:"ORACLE"},
            // props: {
            //   label: "dsName",
            //   value: "id"
            // },
            // dicFormatter: res => {
            //   return res.data.records; //返回字典的層級結構
            // },
            span: 24,
            rules: [
              {
                required: true,
                message: this.$t("sourceSysMessage"),
                trigger: "blur"
              }
            ]
          },
          {
            label: this.$t("sourceTable"),
            prop: "sourceTable",
            type: "select",
            clearable: false,
            dicFlag: false,
            dicUrl:
              "/emptech-middle/dataTable/getTablesByDataBase?dsId={{key}}",
            props: {
              label: "tableName",
              value: "tableName"
            },
            search: true,
            searchslot: true, //使用插槽
            span: 24,
            rules: [
              {
                required: true,
                message: this.$t("sourceTbMessage"),
                trigger: "blur"
              }
            ]
          },

級聯這裏,第一個字段要配置cascaderItem屬性,指定要關聯的字段,然後被關聯的字段,屬性要配置dicFlag: false,否則界面第一次加載時,被關聯的字典接口就會自動請求一次。

需要主意的是,如果sourceDatasource配置爲dicUrl加載字典的方式,每次界面加載的時候,會調用這個字典接口兩次,所以可以採用dicData: []的形式,在mounted中獲取字典數據,然後給字典數據賦值的方式,如下代碼所示:

  async mounted() {//添加字典
    await this.initDictData();
    let sourceSysColumn = this.findObject(
      this.option.column,
      "sourceDatasource"
    );
    sourceSysColumn.dicData = this.sourceSysDicData;
  },
  methods: {
    //初始化字典數據
    async initDictData() {
      let res = await getDataSourceList(1, 100, {
        descs: "create_time",
        dsType: "ORACLE"
      });
      if (res.data.code == 200) {
        this.sourceSysDicData = res.data.data.records.map(m => {
          return {
            value: m.id,
            label: m.dsName
          };
        });
      }
    },

自定義搜索

如下圖所示,原表是一個下拉框字典,搜索的時候,需要是一個文本框模糊搜索:

js代碼如下:

 {
            label: this.$t("sourceTable"),
            prop: "sourceTable",
            type: "select",
            clearable: false,
            dicFlag: false,
            dicUrl:
              "/emptech-middle/dataTable/getTablesByDataBase?dsId={{key}}",
            props: {
              label: "tableName",
              value: "tableName"
            },
            search: true,
            searchslot: true, //使用插槽
            span: 24,
            rules: [
              {
                required: true,
                message: this.$t("sourceTbMessage"),
                trigger: "blur"
              }
            ]
          },

html代碼如下:

    <avue-crud
      :search.sync="query"
      :option="option"
      :table-loading="loading"
      :data="tbData"
      ref="crud"
      v-model="form"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :page.sync="page"
    >
      <template slot-scope="scope" slot="sourceTableSearch">
        <el-input
          :placeholder="$t('sourceTbSearchPlaceholder')"
          :size="size"
          col="6"
          v-model="query.sourceTable"
        ></el-input>
      </template>

通過插槽,插槽名字爲字段名稱+Search,此處爲sourceTableSearch

 彈窗表單中字段間的交互

如下圖所示,當最大可同步範圍選擇“自然月”時,下面展示是否支持跨周,否則不展示:

js代碼:

          {
            label: this.$t("taskManage.maxSynchronizedRange"),
            prop: "maxSyncType",
            type: "select",
            hide: true,
            span: 24,
            value: "1", //默認值,自然周
            clearable: false,
            rules: [
              {
                required: true,
                message: this.$t("taskManage.maxSynchronizedRangeMessage"),
                trigger: "blur"
              }
            ],
            dicData: [],
            // dicUrl:
            //   "/emptech-system/dict-biz/dictionary?code=data_sync_max_scope_type",
            // props: {
            //   label: "dictValue",
            //   value: "dictKey"
            // },
            control: (val, form) => {
              console.log("數據", val);
              if (val == 2) {
                //自然月
                return {
                  isCrossWeek: {
                    display: true
                  }
                };
              } else {
                return {
                  isCrossWeek: {
                    display: false
                  }
                };
              }
            }
          },
          {
            label: this.$t("taskManage.isCrossWeek"),
            prop: "isCrossWeek",
            type: "radio",
            value: "1", //默認值,是
            viewDisabled: true,
            dicUrl:
              "/emptech-system/dict-biz/dictionary?code=data_sync_is_cross_week",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            hide: true,
            span: 24
          },

html代碼如下所示:

 <template slot-scope="{ row, disabled }" slot="maxSyncTypeForm">
        <div class="form-row">
          <avue-select
            v-model="form.maxSyncType"
            :clearable="false"
            type="select"
            :dic="maxSyncTypeDicData"
            :disabled="disabled"
          ></avue-select>
          <el-tooltip placement="right-start">
            <div slot="content">
              自然周內:如2022年8月1日到2022年8月7日爲一個自然周,自然周內則表示可選時間範圍爲在8月1日到8月7日之間;
              <br />
              自然月內:如2022年8月爲一個自然月,自然月內則表示可選時間範圍爲<=8月自然月天數。
            </div>
            <i class="el-icon-question icon"></i>
          </el-tooltip>
        </div>
      </template>

在最大可同步範圍字段中可以配置control方法來控制其它字段的隱藏或者顯示,當然也可以通過watch的方式,後面會說到。

 自定義日期時間範圍搜索條件

需求如下圖所示,這個執行時間範圍只是一個搜索條件,並不會在表格中進行展示,日期時間範圍組件默認顯示當前時間+00:00:00 到當前時間23:59:59,選擇其它日期時,起止時間的時分秒的範圍也默認是00:00:00到23:59:59。

js代碼如下:

          {
            label: this.$t("executingTimeRange"),
            prop: "executingTimeRange",
            type: "datetimerange",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            hide: true,
            display: false,
            search: true,
            searchSpan: 5,
            searchslot: true, //使用插槽
            searchRange: true,
            span: 24,
            searchSpan: 8
          },

html代碼:

      <!-- 自定義搜索卡槽 -->
      <template slot="executingTimeRangeSearch" slot-scope="scope">
        <el-date-picker
          style="width:360px"
          v-model="executingTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="開始日期"
          end-placeholder="結束日期"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
        >
        </el-date-picker>
      </template>

data代碼:

      executingTimeRange: [getCurTimeStart(), getCurTimeEnd()], //執行時間範圍

查詢代碼需要改造:

    //查詢
 searchChange(params, done) {
if (this.executingTimeRange&&this.executingTimeRange.length == 2) {
   params.startExecuteTime = getStrToDatetime(this.executingTimeRange[0]);
   params.endExecuteTime = getStrToDatetime(this.executingTimeRange[1]);
   }
      this.page.currentPage = 1;
      this.query = params;
      this.onLoad(this.page, params);
      done();
    },

彈窗表單自定義驗證

 需求,需要驗證所選的日期範圍是自然周,還是在一個月內,或者是一個月內的自然周內。

 js代碼如下:

    //新增
    rowSave(row, done, loading) {
      console.log("新增", row);
      let flag = this.dataValidate(row);
      if (!flag) {
        loading();
        return;
      }
      // retrun;
      let item = this.createItem(row);
      add(item).then(
        res => {
          this.$message({
            type: "success",
            message: this.$t("successMessage")
          });
          // 數據回調進行刷新
          this.onLoad(this.page);
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    //數據校驗
    dataValidate(row) {
      console.log("查詢", row, this.query);
      let dateRange = row.dateRange;
      if (dateRange.length < 2) {
        this.$message({
          message: "請選擇日期範圍",
          type: "warning"
        });
        return false;
      }
      let res = true;
      let message = "";
      if (this.maxSynchronizedRange == MAXSYNCRANGE.week) {
        //
        res = isSameWeek(dateRange);
        message = "選擇的日期範圍必須是在同一周內";
      } else {
        //
        if (this.isCrossWeek == 0) {
          //不跨周
          res = isSameMonthNoCrossWeek(dateRange);
          message = "選擇的日期範圍必須是在同一月同一周內";
        } else {
          //跨周
          res = isSameMonth(dateRange);
          message = "選擇的日期範圍必須是在同一月內";
        }
      }if (res == false) {
        this.$message({
          message: message,
          type: "warning"
        });
      }
      return res;
    },

注意這個loading()是關閉按鈕的loading的意思。done()方法是關閉彈窗的意思。

文檔中沒有說明的一些隱藏屬性

column中

hide:不在表格列表中顯示。

用到的一些日期相關的方法

日期處理使用的是moment.js,網址:http://momentjs.cn/

/*
 *判斷是否在同一個星期裏
 *dateArr:時間字符串數組
 *return:true/false
 */
export function isSameWeek(dateArr) {
    return moment(dateArr[0]).isSame(dateArr[1], 'week');
}
/*
 *判斷是否在同一個月
 *dateArr:時間字符串數組
 *return:true/false
 */
export function isSameMonth(dateArr) {
    return moment(dateArr[0]).isSame(dateArr[1], 'month');
}
/**
 * 判斷是否在一個月內,且不跨周
 * @param {*} dataArr 
 */
export function isSameMonthNoCrossWeek(dateArr) {
    let start = moment(dateArr[0]).isoWeekday();
    let end = moment(dateArr[1]).isoWeekday();

    let startDay = moment(dateArr[0]).dayOfYear();
    let endDay = moment(dateArr[1]).dayOfYear();

    let sameMonth = isSameMonth(dateArr);
    let sameWeek = (endDay - startDay < 7) && (start <= end);
    return sameMonth && sameWeek; //同月同周
}
/**
 * 獲取當天開始時間
 * @returns 
 */
export function getCurTimeStart() {
    return moment(moment().format('YYYY-MM-DD') + ' 00:00:00').toDate();
}
/**
 * 獲取當天結束時間
 * @returns 
 */
export function getCurTimeEnd() {
    return moment(moment().format('YYYY-MM-DD') + ' 23:59:59').toDate();
}
/**
 * 字符串
 * @param  str
 * @returns 
 */
export function getStrToDatetime(str) {
    return moment(str).format('YYYY-MM-DD HH:mm:ss')
}

後面後再不斷補充.......

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章