vue封装添加编辑模态框共用的方法

在data里面设置变量

      dialog: {
        show: false,
        title: "",
        option: "",
      },

html代码

//添加
<el-button type="primary" @click="addRoles">添加角色</el-button>

//编辑
<el-table-column label="操作" width="300px">
    <template slot-scope="scope">
       <el-button size="mini" type="primary" icon="el-icon-edit" @click="eitRoles(scope.row)">编辑</el-button>
    </template>
</el-table-column>

//模态框
    <el-dialog :title="dialog.title" :visible.sync="dialog.show" width="30%">
      
      <el-form
        :model="ruleForm"
        status-icon
        :rules="from_rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input type="text" v-model="ruleForm.roleName" ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input type="text" v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

点击添加打开模态框

    // 添加角色
    addRoles() {
      this.ruleForm={
        roleName:"",
        roleDesc:""
      };
      this.dialog = {
        show: true,
        title: "添加用户",
        option: "add",
      };
    },

点击编辑打开模态框

    // 编辑角色
    eitRoles(value) {
      console.log(value);
      this.dialog = {
        show: true,
        title: "编辑用户",
        option: "edit",
      };
      this.ruleForm={
        roleName:value.roleName,
        roleDesc:value.roleDesc,
        id:value.id
      }
    },

点击确认按钮判断是添加还是编辑

    onSubmit() {
      this.$refs.cateForm.validate(async (valid) => {
        if (valid) {
          if (this.dialog.option == "edit") {
            const { data: res } = await qqq(this.addCateForm);//qqq请求接口名
            if (res.meta.status !== 200) {
              return this.$message.error("编辑失败!");
            }
            this.$message.success("编辑成功!");
          } else if (this.dialog.option == "add") {
            const { data: res } = await qqq(this.addCateForm);//qqq请求接口名
            if (res.meta.status !== 201) {
              return this.$message.error("添加失败!");
            }
            this.$message.success("添加成功!");
          }
          this.dialog.show = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

猜你喜欢

转载自blog.csdn.net/dyx001007/article/details/127574675
今日推荐