成功vue未保存切换页面提示

<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules2" label-width="120px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="添加时间" prop="addtime">
        <el-date-picker
          v-model="form.addtime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="数量" prop="num1">
        <el-input
          type="text"
          oninput="value=value.replace(/[^\d]/g,'')"
          maxlength="9"
          v-model="form.num1"
          placeholder="请输入数量"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" @click="modify()">确定修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getInfo, modify } from "@/api/test";
export default {
  data() {
    return {
      form: {},
      rules2: {},
      ModifyCount: 0,
    };
  },
  beforeRouteLeave(to, from, next) {
    if (this.ModifyCount > 1) {
      // 这里需要elementui的支持,如果使用其他界面组件自行替换即可
      this.$confirm("您有数据未保存,离开后所有未保存数据都会丢失", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 正常跳转
          next();
        })
        .catch(() => {
          // 如果取消跳转地址栏会变化,这时保持地址栏不变
          window.history.go(1);
        });
    } else {
      next();
    }
  },
  watch: {
    form: {
      handler(newValue, oldValue) {
        this.ModifyCount = this.ModifyCount + 1;
      },
      deep: true, //是否深度侦听,true开启,false关闭,默认false
    },
  },
  mounted() {
    var id = this.$route.query.id;
    this.loadData(id);
  },
  methods: {
    modify() {
      //先判断表单是否通过了判断
      this.$refs.form.validate((valid) => {
        //代表通过验证 ,将参数传回后台
        if (valid) {
          let params = Object.assign({}, this.form);
          modify(params).then((res) => {
            this.$message({
              type: "info",
              message: res.Message,
            });
            this.$router.push("/test_list");
          });
        }
      });
    },
    loadData(id) {
      getInfo(id).then((result) => {
        var _data = result.Data;
        this.form = Object.assign({}, _data);
      });
    },
  },
};
</script>

(0)

相关推荐