当前位置: 首页 > article >正文

Vue3+setup实现父子组件单表增删改查写法模板

父组件写法

<el-card>
        <!-- el-card 头部插槽 显示列表名和新增按钮 -->
        <template #header>
          <div class="table-header-container">
            <i class="fas fa-th" />角色列表(100)
            <span style="flex-grow: 1" />
            &nbsp;&nbsp;&nbsp;
            <!-- 新增按钮 -->
            <el-button
              icon="fas fa-plus"
              type="text"
              style="margin: -10px 0px"
              @click="click_Add_Roles"
              >&nbsp;新增监管角色</el-button
            >
          </div>
        </template>
        <!-- el-table  显示表格  :data绑定数据-->
        <el-table :data="tableData_List" :height="650" stripe ref="userTable">
          <el-table-column
            label="序号"
            type="index"
            :min-width="100"
            fixed
            align="center"
          />
          <el-table-column
            label="编码"
            prop="code"
            width="300"
            sortable
            align="center"
          />
          <el-table-column
            label="名称"
            prop="name"
            width="180"
            sortable
            align="center"
          />
          <el-table-column
            label="创建时间"
            prop="createdTime"
            :formatter="formatDate"
            width="180"
            sortable
            align="center"
          />
          <el-table-column
            label="更新时间"
            prop="updatedTime"
            :formatter="formatDate"
            width="180"
            sortable
            align="center"
          />
          <el-table-column label="备注" prop="remark" align="center">
          </el-table-column>
          <el-table-column label="操作" align="center" :min-width="120">
            <template #default="{ row }">
              <i
                class="fas fa-edit"
                style="cursor: pointer; color: #409eff"
                @click="click_Edit(row)"
              />
              <i
                class="fas fa-trash-alt"
                style="cursor: pointer; color: red"
                @click="click_Delete(row)"
              />
            </template>
          </el-table-column>
        </el-table>
        <!-- 新增表单弹窗子组件 传入属性值及方法 -->
        <AddRolesDialog
          ref="AddRolesDialogRef"
          :option="optionRoles"
          :rowData="rowDataRoles"
          :formTitle="formTitleRoles"
          @closeAuthorizeChildDialog="closeAuthorizeChildDialog"
          @get_SupRoles_List="get_SupRoles_List"
        ></AddRolesDialog>
      </el-card>
<script lang="ts" setup>
// 引入ui组件 加载效果及消息提示
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
// 引入moment插件
import moment from "moment";
import {
  computed,
  getCurrentInstance,
  onMounted,
  ref,
  defineProps,
  nextTick,
  watch,
  reactive,
} from "vue";

// 引入api 可以是自己封装好的也可以是axios
import axios from "axios";
import { BAD_DATA_DISPLAY_CONTENT } from "@/constant";
// 引入新增表单弹窗子组件
import AddRolesDialog from "./AddRolesDialog.vue";
const { proxy }: any = getCurrentInstance();

// 利用moment格式化时间绑定表格创建时间更新时间等
function formatDate(_row: any, _column: any, cellValue?: Date) {
  if (cellValue) {
    return moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
  }
  //   定义好的常量  例如"--"
  return BAD_DATA_DISPLAY_CONTENT;
}
// ----------------------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------------------
// 定义子组件弹窗开关的布尔值和当前操作的表格行数据
const optionRoles = ref({
  dialogAuthorizeChildVisible: false,
  currectRowData: {},
});
// 定义子组件弹窗标题
const formTitleRoles = ref("新增监管角色");
// 定义表格当前行数据
const rowDataRoles = ref({});
// 定义子组件ref
const AddRolesDialogRef: any = ref();
// 定义表格数据源
const tableData_List: any = ref([]);

//打开新增表单 更新属性值状态
const click_Add_Roles = () => {
  optionRoles.value.dialogAuthorizeChildVisible = true;
  formTitleRoles.value = "新增监管角色";
};
// 定义关闭子组件弹窗方法
const closeAuthorizeChildDialog = () => {
  optionRoles.value.dialogAuthorizeChildVisible = false;
};
// 定义编辑表格行方法 更改属性值 调用子组件编辑方法
const click_Edit = (row: any) => {
  formTitleRoles.value = "修改监管角色";
  rowDataRoles.value = row;
  AddRolesDialogRef.value.editToForm(row);
  optionRoles.value.dialogAuthorizeChildVisible = true;
};
// 定义表格行数据删除方法
const click_Delete = (row: any) => {
  ElMessageBox.confirm(`确定删除该角色吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      proxy.axios
        .delete(`/pcadmin/regulator-role-manage/roles/${row.id}`)
        .then(({ data }: { data: any }) => {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          get_SupRoles_List();
        })
        .catch((err: any) => {
          console.error(err);
        });
    })
    .catch(() => {});
};

// 获取监管角色列表
const get_SupRoles_List = () => {
  let loadingInstance: any = null;
  loadingInstance = ElLoading.service({
    lock: true,
    text: "加载中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  proxy.axios
    .get(`/pcadmin/regulator-role-manage/roles`)
    .then(({ data }: { data: any }) => {
      console.log(data, "获取列表");
      tableData_List.value = [];
      tableData_List.value = data.data;
      if (loadingInstance) {
        loadingInstance.close();
      }
    })
    .catch((err: any) => {
      console.error(err);
      if (loadingInstance) {
        loadingInstance.close();
      }
    });
};

onMounted(() => {
  get_SupRoles_List();
});
</script>


子组件写法

<!-- 显示自定义弹窗 绑定弹窗关闭打开关闭方法及是否显示弹窗标题-->
  <el-dialog
    @close="closeAuthorizeChildDialog"
    @open="clearForm"
    v-model="option1"
    :title="props.formTitle"
    width="30%"
  >
    <el-form :model="form">
      <el-form-item label="编码" prop="code" :label-width="formLabelWidth">
        <el-input
          placeholder="请输入"
          class="inputForm"
          v-model="form.code"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name" :label-width="formLabelWidth">
        <el-input
          placeholder="请输入"
          class="inputForm"
          v-model="form.name"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
        <el-input
          placeholder="请输入内容"
          class="inputForm"
          v-model="form.remark"
          type="textarea"
        />
      </el-form-item>
      <el-form-item
        label="序列号"
        prop="sortOrder"
        :label-width="formLabelWidth"
      >
        <el-input
          placeholder="请输入"
          class="inputForm"
          v-model="form.sortOrder"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeAuthorizeChildDialog">取消</el-button>
        <el-button type="primary" @click="onClick_SaveForm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
<script lang="ts" setup>
import {
  ref,
  defineProps,
  reactive,
  onMounted,
  toRef,
  defineEmits,
  getCurrentInstance,
  computed,
  defineExpose,
} from "vue";
import { ElMessage } from "element-plus";
// 引入api 可以是自己封装好的也可以是axios
import axios from "axios";
const { proxy }: any = getCurrentInstance();
// 接受父组件传过来的数据
const props = defineProps({
  option: Object,
  rowData: Object,
  formTitle: String,
});
// 表单label宽度
const formLabelWidth = "60px";
// 将父组件传来的option通过toRef转换成响应式数据
const option = toRef(props, "option");
// 接收父组件传来的方法
const emit = defineEmits(["closeAuthorizeChildDialog", "get_SupRoles_List"]);
// 定义form表单初始数据
const form: any = reactive({
  id: "",
  code: "",
  name: "",
  sortOrder: "",
  remark: "",
});
//周期函数
onMounted(() => {
  //打印父组件传递的值
});
// 定义清空form表单数据方法 判断只有新增的时候清空,编辑不清空
const clearForm = () => {
  if (props.formTitle == "新增监管角色") {
    form.code = "";
    form.name = "";
    form.sortOrder = "";
    form.remark = "";
    form.id = "";
  }
};
// 定义编辑form表单方法 接收实参,形参赋值,拿到要编辑行数据的id
const editToForm = (val: any) => {
  form.id = val.id;
  form.code = val.code;
  form.name = val.name;
  form.sortOrder = val.sortOrder;
  form.remark = val.remark;
};
// 方法暴露给父组件
defineExpose({ editToForm });

// 定义关闭弹窗方法
const closeAuthorizeChildDialog = () => {
  emit("closeAuthorizeChildDialog");
};
// 定义一个新变量,用于控制弹窗双向绑定的布尔值
const option1 = computed({
  get: () => option.value?.dialogAuthorizeChildVisible,
  set: (val: any) => {
    emit("closeAuthorizeChildDialog");
  },
});

//新增编辑保存
const onClick_SaveForm = () => {
  // 关闭弹窗
  closeAuthorizeChildDialog();
  //   判断是编辑还是新增
  if (props.formTitle == "新增监管角色") {
    let params = {
      code: "",
      name: "",
      sortOrder: "",
      remark: "",
    };
    params.code = form.code;
    params.name = form.name;
    params.sortOrder = form.sortOrder;
    params.remark = form.remark;
    proxy.axios
      .post(`/pcadmin/regulator-role-manage/roles`, params)
      .then(({ data }: { data: any }) => {
        if (data.errorcode == 0) {
          ElMessage.success("新增成功!");
          emit("get_SupRoles_List");
        } else {
          ElMessage.warning(data.message);
        }
      })
      .catch((err: any) => {
        console.error(err);
        ElMessage.warning(err);
      });
  } else {
    let params = {
      code: "",
      name: "",
      sortOrder: "",
      remark: "",
    };
    params.code = form.code;
    params.name = form.name;
    params.sortOrder = form.sortOrder;
    params.remark = form.remark;
    proxy.axios
      .put(`/pcadmin/regulator-role-manage/roles/${form.id}`, params)
      .then(({ data }: { data: any }) => {
        if (data.errorcode == 0) {
          ElMessage.success("编辑成功!");
          emit("get_SupRoles_List");
        } else {
          ElMessage.warning(data.message);
        }
      })
      .catch((err: any) => {
        ElMessage.warning(err);
        console.error(err);
      });
  }
};
</script>


http://www.kler.cn/a/299064.html

相关文章:

  • 最新ubuntu20.04安装docker流畅教程
  • centos7下docker 容器实现redis主从同步
  • android recycleview 中倒计时数据错乱
  • LeetCode刷题day29——动态规划(完全背包)
  • Day45 动态规划part12
  • run postinstall error, please remove node_modules before retry!
  • 828华为云征文|华为云Flexus X实例docker部署mediacms,功能齐全的现代化开源视频和媒体CMS
  • axure判断
  • k8s HPA
  • 进程查看和计划任务
  • web渗透:RCE漏洞
  • k8s防火墙networkPolicy,的核心是“自己”
  • 苹果首款AI手机发布!iPhone 16全新AI功能体验感拉满
  • Unity报错:error CS8805: Program using top-level statements must be an executable.
  • Guitar Pro 8.2中文解锁版下载及2024最新图文安装教程
  • (Java企业 / 公司项目)点赞业务系统设计与完成
  • 智能优化算法-樽海鞘优化算法(SSA)(附源码)
  • Qt绘图之平移、旋转、缩放
  • Flex布局最后一行元素的对齐的解决方案
  • 《华为 eNSP 模拟器安装教程》
  • Spring Boot详解
  • 组织应在其网络安全策略中考虑MLSecOps吗?
  • LCR 021
  • SpringBoot2:请求处理原理分析-接口方法的返回值处理(returnValueHandlers)
  • Redis 入门 - 五大基础类型及其指令学习
  • 【安卓13 源码】Input子系统(3) - EventHub增加设备的流程