el-table-column嵌套el-autocomplete使用

文章介绍了如何在Vue.js项目中使用el-table-column组件结合el-autocomplete实现表格内的行内编辑功能,特别是数据的增删改查操作。通过循环列表项动态生成列,并展示了编辑模式下el-autocomplete的用法,包括查询、选择和回填数据的逻辑处理。同时,文章提出了在el-table中ref属性生成两个节点的问题,邀请读者讨论。

项目场景:

项目场景:当表格内容较少时,可简便为直接进行,行内编辑数据,进行增删改查操作(文章最后有全部代码,可自行尝试)
在这里插入图片描述

解决方法

首先单独讲解一下el-table-column嵌套el-autocomplete的写法以及代码逻辑,最后贴完整代码

循环列表项
<jr-table-column
        :label="item.label"
        v-for="item in columnList"   
        :key="item.prop"
      >
        <template slot-scope="scope">
          <template v-if="state == 'edit'">
          	
            <el-autocomplete
              v-if="item.prop == 'relatedPartyName'"
              popper-class="el-autocomplete-suggestion"
              style="width: 100%"
              clearable
              ref="modelRef"
              v-model="scope.row[item.prop]"
              :fetch-suggestions="querySearch"
              placeholder="请输入名称"
              @select="
                (item) => {
                  handleSelect(item, scope.$index);     查询到可选项列表后选择对应那条数据(scope.$index确定它在列表的哪一行)
                }
              "
            >
              <el-button
                slot="append"
                style="width: 60px"
                :loading="queryCarLoading"
                @click="queryCarFun(scope.$index)"     点击放大镜按钮方法
              >
                <i class="el-icon-search" v-if="!queryCarLoading"></i>
              </el-button>
            </el-autocomplete>
            <el-input
              v-else
              v-model="scope.row[item.prop]"
              class="edit-input"
              size="mini"
            />
          </template>
        </template>
      </jr-table-column>
data() {
    return {
      columnList: [
        {
          prop: "statDate",
          label: "测试数据",
        },
        {
          prop: "relatedPartyType",
          label: "测试数据111",
        },
        {
          prop: "relatedPartyName",
          label: "测试数据222",
        },
        {
          prop: "corpUniscCode",
          label: "测试数据333",
        },
        {
          prop: "corpInvestFund",
          label: "测试数据4444",
        },
      ],
      state: "",
      querySearchName: "",
      queryCarLoading: false,
      queryFlag: false,
      queryRes: [],
    };
  },
   methods: {
    querySearch(queryString, cb) {
      this.querySearchName = queryString;
      if (this.queryFlag) {
        cb(this.queryRes);
        this.queryFlag = false;
      } else {
        cb(this.queryRes || []);
      }
    },
    //名称选择值后(这块的处理是因为我选择需要的那条后,还要把对应的某个字段放入列表的行内,所以有特殊处理)
    handleSelect(val, index) {
      this.d03List[index].relatedPartyCode = val.relatedPartyCode;
      this.d03List[index].corpUniscCode = val.corpUniscCode;
    },
    //点击名称查询放大镜按钮
    queryCarFun(val) {
      let info = {
        relatedname: this.querySearchName,
        relatedPartyType: this.d03List[val].relatedPartyType || "",
      };
      this.queryCarLoading = true;
      queryRelatedParty(info).then((res) => {
        this.queryFlag = true;
        this.queryCarLoading = false;
        //这块是重点,查询后台获取到数据后,要放入el-autocomplete所需要的格式中,value代表弹出展示的名称
        this.queryRes = res.data.map((item) => ({
          // ...item,
          relatedPartyCode: item.relatedcode,
          corpUniscCode: item.identityNo,
          value: item.relatedname,
        }));
        if (this.queryRes.length === 0) {
          this.$message.warning("未查询到其名称,请修改后重新查询");
        } else {
          //.focus()是为了让查询到数据后自动弹出可选项的列表(如果el-autocomplete放在el-dialog组件,我们可以直接使用this.$refs.modelRef弹出,但是放在el-table-column,他会生成两条,所以只能去计算弹出,)
          //可以打印一下this.$refs.modelRef就会明白我说的什么意思
          // console.log(this.$refs.modelRef);
          //每新增一行都有添加两条this.$refs.modelRef,只有新增那一行的第一条才可以显示打开查询的列表,所以要获取表格的第几行val然后X2
          this.$refs.modelRef[val * 2].focus();
        }
      });
    },
  },

在这里插入图片描述
在这里插入图片描述

全部代码逻辑

以下是全部代码,自行替换所需的接口即可尝试

<template>
  <div>
    <div>
      <el-button
        type="primary"
        size="mini"
        @click="edit"
        >编辑</el-button
      >
      <el-button type="success" size="mini" @click="save" 
        >保存</el-button
      >
    </div>
    <jr-table :showPagination="false" :height="'300'" :tableData="d03List">
      <jr-table-column label="序号" type="index" width="50"></jr-table-column>
      <jr-table-column
        :label="item.label"
        v-for="item in columnList"
        :key="item.prop"
      >
        <template slot-scope="scope">
          <template v-if="state == 'edit'">
            <el-autocomplete
              v-if="item.prop == 'relatedPartyName'"
              popper-class="el-autocomplete-suggestion"
              style="width: 100%"
              clearable
              ref="modelRef"
              v-model="scope.row[item.prop]"
              :fetch-suggestions="querySearch"
              placeholder="请输入名称"
              @select="
                (item) => {
                  handleSelect(item, scope.$index);
                }
              "
            >
              <el-button
                slot="append"
                style="width: 60px"
                :loading="queryCarLoading"
                @click="queryCarFun(scope.$index)"
              >
                <i class="el-icon-search" v-if="!queryCarLoading"></i>
              </el-button>
            </el-autocomplete>
            <el-input
              v-else
              v-model="scope.row[item.prop]"
              class="edit-input"
              size="mini"
            />
          </template>
          <template v-else>
            <span>{{ scope.row[item.prop] }}</span>
          </template>
        </template>
      </jr-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="190"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
            @click="handleAdd(scope.$index, scope.row)"
          >
            新增
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click.native.prevent="deleteRow(scope.$index, d03List)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </jr-table>
  </div>
</template>
<script>
import { saveMonthD03, queryRelatedParty } from "@/api/gljyData/gljyjcData";
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState("common", [
    ]),
  },
  props: {
    d03List: Array,
  },
  data() {
    return {
      columnList: [
        {
          prop: "statDate",
          label: "测试数据",
        },
        {
          prop: "relatedPartyType",
          label: "测试数据111",
        },
        {
          prop: "relatedPartyName",
          label: "测试数据222",
        },
        {
          prop: "corpUniscCode",
          label: "测试数据333",
        },
        {
          prop: "corpInvestFund",
          label: "测试数据4444",
        },
      ],
      state: "",
      querySearchName: "",
      queryCarLoading: false,
      queryFlag: false,
      queryRes: [],
    };
  },
  created() {},
  mounted() {},
  methods: {
    querySearch(queryString, cb) {
      this.querySearchName = queryString;
      if (this.queryFlag) {
        cb(this.queryRes);
        this.queryFlag = false;
      } else {
        cb(this.queryRes || []);
      }
    },
    //名称选择值后
    handleSelect(val, index) {
      this.d03List[index].relatedPartyCode = val.relatedPartyCode;
      this.d03List[index].corpUniscCode = val.corpUniscCode;
    },
    //点击名称查询放大镜按钮
    queryCarFun(val) {
      let info = {
        relatedname: this.querySearchName,
        relatedPartyType: this.d03List[val].relatedPartyType || "",
      };
      this.queryCarLoading = true;
      queryRelatedParty(info).then((res) => {
        this.queryFlag = true;
        this.queryCarLoading = false;
        this.queryRes = res.data.map((item) => ({
          // ...item,
          relatedPartyCode: item.relatedcode,
          corpUniscCode: item.identityNo,
          value: item.relatedname,
        }));
        if (this.queryRes.length === 0) {
          this.$message.warning("未查询到其名称,请修改后重新查询");
        } else {
          // console.log(this.$refs.modelRef.length);
          //每新增一行都有添加两条this.$refs.modelRef,只有新增那一行的第一条才可以显示打开查询的列表,所以要获取表格的第几行val然后X2
          this.$refs.modelRef[val * 2].focus();
        }
      });
    },
    //保存
    save() {
      console.log(this.d03List);
      if (this.d03List && this.d03List.length > 0) {
        saveMonthD03(this.d03List).then((res) => {
          this.state = "";
          this.$emit("saveD03");
          this.$message.success("保存成功");
        });
      } else {
        this.$message.warning("请先编辑数据");
      }
    },
    //编辑
    edit() {
      if (this.d03List && this.d03List.length > 0) {
        this.state = "edit";
      } else {
        this.state = "edit";
        let tableVal = {
          statDate: "",
          relatedPartyType: "",
          relatedPartyName: "",
          relatedPartyCode: "",
          corpUniscCode: "",
          corpInvestFund: "",
        };
        this.d03List.push(tableVal);
      }
    },
    //表格新增
    handleAdd(row, val) {
      this.state = "edit";
      let tableVal = {
        statDate: "",
        relatedPartyType: "",
        relatedPartyName: "",
        relatedPartyCode: "",
        corpUniscCode: "",
        corpInvestFund: "",
      };
      this.queryRes = [];
      this.d03List.push(tableVal);
    },
    //表格删除行
    deleteRow(index, rows) {
      this.$confirm("您现在的操作将删除此条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          rows.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
    },
  },
};
</script>

小疑问:为啥在el-table里会生成this.$refs.modelRef两个节点呢,欢迎各位大佬指点讨论

<template> <h1 style="color: #009dff">部门管理</h1> <br> <el-button type="primary" @click="save">新增部门</el-button> <br><br> <el-table :data="tableData" border :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}" style="width: 100%" > <el-table-column type="index" label="序号" width="180"/> <el-table-column prop="name" label="部门名称" width="180"/> <el-table-column prop="updateTime" label="修改时间"/> <el-table-column fixed="right" label="操作" min-width="120"> <template #default="{row}"> <el-button type="success" size="small" @click="getDeptImpl(row)">编辑</el-button> <el-button type="danger" size="small" >删除</el-button> </template> </el-table-column> </el-table> <!-- 对话框--> <el-dialog v-model="dialogVisible" title="新增部门" width="500" > <el-form ref="formRef" style="max-width: 600px" :model="dept" label-width="auto" class="demo-ruleForm" > <el-form-item label="部门名称" prop="name" :rules="[ { required: true, message: '部门名称必填!' }, // { type: 'String', message: 'age must be a number' }, ]" > <el-input v-model="dept.name" type="text" autocomplete="off" /> </el-form-item> </el-form> <template #footer> <div class="dialog-footer"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="confirm">确定</el-button> </div> </template> </el-dialog> </template> <script lang='ts' setup> import {ref, onMounted} from 'vue' // import axios from "axios"; import {queryAllApi,addDeptApi,getDept} from '@/api/dept' import {ElMessage} from "element-plus"; const tableData = ref([]) let dialogVisible = ref(false)//控制开关 const dept = ref({id:'',name:'',}) const queryAll = async () => { const result = await queryAllApi() tableData.value = result.data } onMounted(() => { queryAll() }) //修改方法 // const handleUpdate = async (id) => { // let result=await handleUpdate(id); // } // //删除方法 // const handleDelete = (id) => { // console.log(id) // } //新增按钮 const save=()=>{ // dept.value={} dept.value = { id:'',name: '' } dialogVisible.value =true } //确定方法 const confirm=async ()=>{ const result=await addDeptApi(dept.value); if(result.code==1){ ElMessage.success("添加成功") queryAll() }else{ ElMessage.error("添加失败") } dialogVisible.value=false; } //回显 const getDeptImpl=async(row)=>{ dialogVisible.value =true let result=await getDept(row.id) dept.value= result.data } </script> <style scoped> </style> 为什么不会回显数据
08-21
<template> <div v-show="active === flag" class="step-main"> <div class="step-content"> <el-form ref="baseForm" :model="baseFormCurr" :rules="rules" label-width="105px"> <el-row :gutter="10"> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="表名称" prop="tableName"> <el-input v-model="baseFormCurr.tableName" autocomplete="off"></el-input> </el-form-item> </el-col> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="表类型" prop="tableType"> <el-select v-model="baseFormCurr.tableType" :disabled="formState.tableType" placeholder="请选择" style="width: 100%" @change="tableTypeChange"> <el-option v-for="item in dictCurr.table_type" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" ></el-option> </el-select> </el-form-item> </el-col> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="描述" prop="comments"> <el-input v-model="baseFormCurr.comments" autocomplete="off" maxlength="100" show-word-limit ></el-input> </el-form-item> </el-col> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="数据库类型" prop="jdbcType"> <el-select ref="jdbcType" v-model="baseFormCurr.jdbcType" :disabled="formState.jdbcType" placeholder="请选择" style="width: 100%" @change="jdbcTypeChange"> <el-option v-for="item in dictCurr.jdbc_type" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" ></el-option> </el-select> </el-form-item> </el-col> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="备注" prop="remark"> <el-input v-model="baseFormCurr.remark" autocomplete="off" maxlength="120" show-word-limit ></el-input> </el-form-item> </el-col> </el-row> </el-form> <vab-query-form> <vab-query-form-left-panel> <el-button :disabled="!baseFormCurr.jdbcType" icon="el-icon-plus" type="primary" @click="columnHandleAdd"> 添加 </el-button> <el-button icon="el-icon-plus" type="primary" @click="dialogVisible = true"> 常用字段 </el-button> <el-button :disabled="!selectRows.length > 0" icon="el-icon-delete" type="danger" @click="columnHandleDelete" > 删除 </el-button> </vab-query-form-left-panel> </vab-query-form> <el-form ref="tableForm" :model="{'tableForm': tableFormCurr}"> <el-table :data="tableFormCurr" :element-loading-text="elementLoadingText" border @selection-change="setSelectRows" > <el-table-column show-overflow-tooltip type="selection"></el-table-column> <el-table-column align="center" label="拖动" show-overflow-tooltip width="60" > <template v-slot="scope"> <el-button circle class="move-btn" icon="el-icon-d-caret" ></el-button> </template> </el-table-column> <el-table-column label="字段名称" min-width="200" prop="fieldName" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldName'" :rules="columnRules.fieldName" class="el-form-item-table" > <el-input v-model="scope.row.fieldName" :disabled="scope.row.disabled" style="width: 100%"/> </el-form-item> </template> </el-table-column> <el-table-column label="字段类型" min-width="180" prop="fieldType" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldType'" :rules="columnRules.fieldType" class="el-form-item-table" > <el-select v-model="scope.row.fieldType" :disabled="scope.row.disabled" default-first-option="" filterable placeholder="请选择" style="width: 100%"> <el-option v-for="item in baseDictData.fieldList" :key="item" :label="item" :value="item" ></el-option> </el-select> </el-form-item> </template> </el-table-column> <el-table-column label="字段长度" min-width="140" prop="fieldLength" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldLength'" class="el-form-item-table" > <el-input-number v-model="scope.row.fieldLength" :disabled="scope.row.disabled" :max="20000" :min="0" controls-position="right" style="width: 100%" ></el-input-number> </el-form-item> </template> </el-table-column> <el-table-column label="字段精度" min-width="140" prop="fieldPrecision" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldComments'" class="el-form-item-table" > <el-input-number v-model="scope.row.fieldPrecision" :disabled="scope.row.disabled" :max="100" :min="0" controls-position="right" style="width: 100%" ></el-input-number> </el-form-item> </template> </el-table-column> <el-table-column label="字段描述" min-width="240" prop="fieldComments" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldComments'" :rules="columnRules.fieldComments" class="el-form-item-table" > <el-input v-model="scope.row.fieldComments" :disabled="scope.row.disabled" maxlength="100" show-word-limit style="width: 100%"/> </el-form-item> </template> </el-table-column> <el-table-column label="主键" min-width="80" prop="izPk" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.izPk'" class="el-form-item-table" > <el-switch v-model="scope.row.izPk" :active-value="1" :disabled="scope.row.disabled" :inactive-value="0" @change="pKChange(scope.row)" > </el-switch> </el-form-item> </template> </el-table-column> <el-table-column label="非空" min-width="80" prop="izNotNull" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.izNotNull'" class="el-form-item-table" > <el-switch v-model="scope.row.izNotNull" :active-value="1" :disabled="scope.row.disabled || scope.row.izPk === 1" :inactive-value="0" > </el-switch> </el-form-item> </template> </el-table-column> </el-table> </el-form> </div> <step-footer ref="step-footer" :flag="flag" :info-data="{ obj: this, baseForm: baseFormCurr, tableForm: tableFormCurr }" :max-flag="maxFlag" :min-flag="minFlag" ></step-footer> <!-- 选择预制字段--> <el-dialog :before-close="handleClose" :visible.sync="dialogVisible" append-to-body title="选择常见字段" width="30%"> <div> <template v-for="item in BuiltInFields"> <el-checkbox v-model="BuiltInFieldsSelect" :label="item.fieldName" border style="margin: 5px" @change="changeBuiltInFieldsSelect"></el-checkbox> </template> </div> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="AddDefaultFields">确 定</el-button> </span> </el-dialog> </div> </template> <script> import {isCode, isNull} from "@/utils/validate"; import StepFooter from "./footer/StepFooter.vue" import {deepClone} from "@/utils/clone"; import Sortable from "sortablejs"; import {uuid} from "@/utils"; import {getFieldTypes, getJavaFieldTypesBySafety} from "@/api/generator/tableManagement"; import {isNotNull} from "@/utils/valiargs"; import { useGlobalStore } from '@/pinia/global'; let state = useGlobalStore(); export default { name: "TableDataStep", components: {Sortable, StepFooter}, props: { active: { type: Number, default: () => { return 1; }, }, minFlag: { type: Number, default: () => { return 1; }, }, maxFlag: { type: Number, default: () => { return 1; }, }, baseForm: { type: Object, default: () => { return {}; }, }, tableForm: { type: Array, default: () => { return []; }, }, dict: { type: Object, default: () => { return {}; }, }, baseDictData: { type: Object, default: () => { return { fieldList: [], JavaFieldMap: {}, }; }, } }, data() { const validateTableName = (rule, value, callback) => { if (isNull(value)) { callback(new Error("请输入表名")); } if (!isCode(value)) { callback(new Error("表名只能为字母、数字或下划线")); } else { callback(); } }; const validateName = (rule, value, callback) => { if (!isCode(value)) { callback(new Error("只能为字母、数字或下划线")); } else { callback(); } }; return { BuiltInFieldsSelect: [],//已选中的字段 BuiltInFields: [ { "encryptData": null, "fieldName": "id", "fieldType": "bigint", "fieldLength": 19, "fieldPrecision": 0, "fieldComments": "唯一主键", "izPk": 1, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 0, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "org_ids", "fieldType": "varchar", "fieldLength": 500, "fieldPrecision": 0, "fieldComments": "父级主键集合", "izPk": 0, "izNotNull": 0, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 1, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "tenant_id", "fieldType": "bigint", "fieldLength": 19, "fieldPrecision": 0, "fieldComments": "多租户ID", "izPk": 0, "izNotNull": 0, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 8, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "create_by", "fieldType": "bigint", "fieldLength": 19, "fieldPrecision": 0, "fieldComments": "创建者", "izPk": 0, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 10, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "create_time", "fieldType": "datetime", "fieldLength": 0, "fieldPrecision": 0, "fieldComments": "创建时间", "izPk": 0, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 11, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "update_by", "fieldType": "bigint", "fieldLength": 19, "fieldPrecision": 0, "fieldComments": "修改人", "izPk": 0, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 12, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "update_time", "fieldType": "datetime", "fieldLength": 0, "fieldPrecision": 0, "fieldComments": "修改时间", "izPk": 0, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 13, "validateType": null, "queryType": null, "disabled": false }, { "fieldName": "delected", "sort": 8, "izPk": 0, "izNotNull": 1, "izShowList": 0, "izShowForm": 0, "queryType": "", "fieldType": "int", "fieldLength": 1, "fieldPrecision": 0, "fieldComments": "删除", "javaType": "", "validateType": "", "showType": "", "dictTypeCode": "", "disabled": false }, { "fieldName": "version", "sort": 8, "izPk": 0, "izNotNull": 1, "izShowList": 0, "izShowForm": 0, "queryType": "", "fieldType": "int", "fieldLength": 1, "fieldPrecision": 0, "fieldComments": "乐观锁", "javaType": "", "validateType": "", "showType": "", "dictTypeCode": "", "disabled": false } ], dialogVisible: false,//选址内置字段 // 标示 flag: 1, title: "数据库表设置", dictCurr: [], baseFormCurr: {}, tableFormCurr: [], formState: { jdbcType: false, tableType: false, }, rules: { tableName: [ {required: true, trigger: "blur", validator: validateTableName}, ], tableType: [ {required: true, trigger: "change", message: "请选择表类型"}, ], jdbcType: [ {required: true, trigger: "change", message: "请选择数据库类型"}, ], comments: [ {required: true, trigger: "blur", message: "请输入描述"}, ], }, treeName: "parent_id", // 新增字段模版 columnFormTemp: { id: "", sort: 0, izPk: 0, izNotNull: 0, izShowList: 0, izShowForm: 0, queryType: "", fieldName: "", fieldType: "", fieldLength: 0, fieldPrecision: 0, fieldComments: "", javaType: "", validateType: "", showType: "", dictTypeCode: "", disabled: false, }, columnRules: { fieldName: [ {required: true, message: "请选择字段名称", trigger: "blur"}, {required: true, trigger: "blur", validator: validateName}, ], fieldType: [ {required: true, message: "请选择字段类型", trigger: "change"}, ], fieldComments: [ {required: true, message: "请输入字段描述", trigger: "blur"}, ] }, layout: "total, sizes, prev, pager, next, jumper", selectRows: "", elementLoadingText: "正在加载...", }; }, created() { // 告诉父节点 自己的 flag 编号 this.$emit("inform-flag", this.flag, this.title); }, mounted() { // 拷贝 props this.baseFormCurr = deepClone(this.baseForm); this.tableFormCurr = deepClone(this.tableForm); this.dictCurr = deepClone(this.dict); // 数据库字段类型 // this.dictCurr.field_type = this.$getDictList(this.baseFormCurr.jdbcType + "_data_type"); // 改成自己项目的字典项获取方式 // this.dict = state.sysDict; // this.dictCurr.field_type = state.sysDict.table_type; let dataType = this.baseFormCurr.jdbcType + "_data_type"; // JavaScript 对象支持两种属性访问方式:1点符号:object.propertyName ,适用于静态属性名。 2方括号符号:object[propertyName] ,适用于动态属性名,propertyName 可以是一个变量或表达式。 this.dictCurr.field_type = state.sysDict[dataType]; // 表拖动 this.rowDrop(); // 初始化数据 this.doGetFieldData(); }, watch: { baseForm(newV, oldV) { this.baseFormCurr = deepClone(newV); }, tableForm(newV, oldV) { this.tableFormCurr = deepClone(newV); }, dict(newV, oldV) { this.dictCurr = deepClone(newV); // 数据库字段类型 // this.dictCurr.field_type = this.$getDictList(this.baseFormCurr.jdbcType + "_data_type"); // 改成自己项目的字典项获取方式 // this.dict = state.sysDict; // this.dictCurr.field_type = state.sysDict.table_type; let dataType = this.baseFormCurr.jdbcType + "_data_type"; // JavaScript 对象支持两种属性访问方式:1点符号:object.propertyName ,适用于静态属性名。 2方括号符号:object[propertyName] ,适用于动态属性名,propertyName 可以是一个变量或表达式。 this.dictCurr.field_type = state.sysDict[dataType]; }, }, methods: { handleClose() { this.dialogVisible = false }, changeBuiltInFieldsSelect(e) { this.BuiltInFieldsSelect = this.removeElementsFromArray(this.BuiltInFieldsSelect, this.tableFormCurr) }, removeElementsFromArray(A, B) { A = A.filter(a => { let isEqual = B.some(b => b.fieldName === a); if (isEqual) { this.$message.error(`已存在字段:${a}`) } return !isEqual; }); return A; }, //添加默认字段 AddDefaultFields(params) { console.log(this.BuiltInFieldsSelect) for (const param of this.BuiltInFieldsSelect) { this.AddDefaultFields2(param) } this.dialogVisible = false }, //方法2 AddDefaultFields2(title) { let temp = null for (const tempElement of this.BuiltInFields) { if (tempElement.fieldName == title) { temp = tempElement } } this.tableFormCurr.push(temp); }, // 数据库类型发生改动 jdbcTypeChange(newValue) { const _this = this; this.tableFormCurr.jdbcType = this.$refs.jdbcType.value; this.$baseConfirm("更换数据库类型将会清空当前已设字段,你确定要更换吗", null, () => { // 改为新值 _this.tableFormCurr.jdbcType = newValue; // 加载字典 // _this.dictCurr.field_type = _this.$getDictList(_this.baseFormCurr.jdbcType + "_data_type"); // 改成自己项目的字典项获取方式 // this.dict = state.sysDict; // this.dictCurr.field_type = state.sysDict.table_type; let dataType = this.baseFormCurr.jdbcType + "_data_type"; // JavaScript 对象支持两种属性访问方式:1点符号:object.propertyName ,适用于静态属性名。 2方括号符号:object[propertyName] ,适用于动态属性名,propertyName 可以是一个变量或表达式。 this.dictCurr.field_type = state.sysDict[dataType]; // 清空已有字段数据 _this.tableFormCurr = []; // 初始化数据 this.doGetFieldData(); }); }, // 表类型发生改动 tableTypeChange(newValue) { if (newValue === '0') { // 删除 parent_id 字段 for (let i = this.tableFormCurr.length - 1; i >= 0; i--) { let item = this.tableFormCurr[i]; if (item.fieldName === this.treeName) { this.tableFormCurr.splice(i, 1); break; } } } else if (newValue === '1') { // 删除 parent_id 字段 for (let i = this.tableFormCurr.length - 1; i >= 0; i--) { let item = this.tableFormCurr[i]; if (item.fieldName === this.treeName) { this.tableFormCurr.splice(i, 1); break; } } // 增加 parent_id 字段 let tmp = deepClone(this.columnFormTemp); tmp.disabled = true; tmp.fieldName = this.treeName; tmp.fieldType = "bigint"; tmp.fieldLength = 20; tmp.fieldComments = "上级ID"; tmp.javaType = "Integer"; tmp.izNotNull = 1; this.columnHandleAdd(tmp); } }, // 主键改动 pKChange(el) { if (!isNull(el)) { // 如果主键选中 则默认选中不可为空 if (el.izPk === 1) { el.izNotNull = 1; } else { el.izNotNull = 0; } } }, // ============================== async doGetFieldData() { this.$emit("loading"); // 通知父级 锁定当前表 this.$emit("inform-data", { fieldList: await this.doGetFieldTypes(), JavaFieldMap: await this.doGetJavaFieldTypesBySafety(), }); this.$emit("unLoading"); }, // 获得 数据类型 async doGetFieldTypes() { // const { data } = await getFieldTypes(); // 改成自己项目的数据返回格式 const res = await getFieldTypes(); const data = res.result.opsliData.data; if (isNotNull(data)) { return data; } return null; }, // 获得 Java 类型 (安全兜底模式) async doGetJavaFieldTypesBySafety() { // const { data } = await getJavaFieldTypesBySafety(); // 改成自己项目的数据返回格式 const res = await getJavaFieldTypesBySafety(); const data = res.result.opsliData.data; if (isNotNull(data)) { return data; } return null; }, // 行添加 columnHandleAdd(params) { let temp; if (!isNull(params) && !(params instanceof MouseEvent)) { temp = params; } else { temp = deepClone(this.columnFormTemp); } temp.id = "temp_" + uuid() if (this.tableFormCurr == null || this.tableFormCurr.length === 0) { temp.sort = 0; } else { temp.sort = this.tableFormCurr.length; } this.tableFormCurr.push(temp); }, // 行删除 columnHandleDelete(row) { if (row.id) { this.$baseConfirm("你确定要删除当前字段吗", null, () => { for (let i = this.tableFormCurr.length - 1; i >= 0; i--) { let item = this.tableFormCurr[i]; if (item.id === row.id) { // 树装接口 不允许删除 parent_id 字段 if (this.tableFormCurr.tableType === '1') { if (item.fieldName !== this.treeName) { this.tableFormCurr.splice(i, 1); } } else { this.tableFormCurr.splice(i, 1); } break; } } }); } else if (this.selectRows.length > 0) { const ids = this.selectRows.map((item) => item.id); this.$baseConfirm("你确定要删除当前字段吗", null, () => { for (let i = this.tableFormCurr.length - 1; i >= 0; i--) { let item = this.tableFormCurr[i]; if (ids.indexOf(item.id) !== -1) { // 树装接口 不允许删除 parent_id 字段 if (this.tableFormCurr.tableType === '1') { if (item.fieldName !== this.treeName) { this.tableFormCurr.splice(i, 1); } } else { this.tableFormCurr.splice(i, 1); } } } }); } else { this.$baseMessage("未选中任何行", "error"); return false; } }, // 行选中 setSelectRows(val) { this.selectRows = val; }, //行拖拽 rowDrop() { const tbody = this.$refs["tableForm"].$el .querySelector(".el-table__body-wrapper tbody"); const _this = this Sortable.create(tbody, { // 只能纵向拖动 axis: "y", // 限制触发事件只能某个元素可以触发 handle: ".move-btn", // 如果设置成true,则被拖拽的元素在返回新位置时,会有一个动画效果。 revert: true, // 如果设置成true,则元素被拖动到页面边缘时,会自动滚动。 scroll: true, onEnd({oldIndex, newIndex}) { _this.tableFormCurr[oldIndex].sort = newIndex; // 如果是 从后往前 移动 则 当前项改为newIndex 而 原newIndex 往后的所有内容全部向后顺产移动 if (oldIndex > newIndex) { for (let i = oldIndex; i > newIndex; i--) { _this.tableFormCurr[i - 1].sort = i; } } // 如果是 从前往后 移动 则 当前项改为newIndex 而 原newIndex 往后的所有内容全部向前顺产移动 else { for (let i = oldIndex; i < newIndex; i++) { _this.tableFormCurr[i + 1].sort = i; } } } }) }, }, }; </script> 这段代码是一个vue文件, 代码语法的框架是element-ui, 版本是2.15.13。我的前端项目vue版本是3.4.21, 框架ant-design-vue版本是4.2.1。现在的问题是文件内容和项目框架语法不一样, 请帮我把整个文件的代码内容修改成适配我项目框架的语法(注意:我的前端项目vue版本是3.4.21, 框架ant-design-vue版本是4.2.1,必须生成对应版本的语法)。 不要删除里边已经注释的代码, 即使有相同的代码, 你也不要省略代码, 把所有内容全部输出来, 需要保持原有的布局样式而调整转换代码。如果这个文件引入的别的文件, 不用你关心别的文件, 你不要给我生成别的文件内容, 最后生成一个vue文件给我, 如果输出内容过长而被终止截断了,请接着输出剩余的部分。转换后要求代码不报错, 按钮方法和底部方法名称要对应起来, 转换过程中不要遗漏代码, 注意:如果之前代码有$baseConfirm, 给我替换成Modal.confirm , 并且引入import { message, Modal } from “ant-design-vue”; 如果之前代码有$baseMessage, 给我替换成message.success或message.warning或message.error。 你好好思考分析下我的需求,不是将把Element UI组件替换为Ant Design Vue组件,你考虑转换后的版本了吗,不同版本语法api不一样,否则转换后的代码根本不能用。不要给我进行简化处理,方法内容不要给我留空,不要等着我补充,你都给我转换处理好。
08-06
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值