一、触发表单是否返回按钮在父组件,表单在子组件
父组件
<template>
<div>
<div @click="goBack">返回</div>
<FormComponent :echoInfo="echoInfo" @markAsUnsaved="markAsUnsaved"></FormComponent>
</div>
</template>
<script>
import FormComponent from "@/components/FormComponent.vue";
export default {
components: {
FormComponent,
},
data() {
return {
// 如果存在表单回显数据
echoInfo: {},
// 是否修改内容未保存
hasUnsavedChanges: false,
};
},
methods: {
// 返回
goBack() {
if (this.hasUnsavedChanges) {
this.$confirm("您还有编辑内容尚未保存,确定退出吗?", "注意", {
confirmButtonText: "确认",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
// 确认返回后的操作
})
.catch(() => {
this.$message({
type: "info",
message: "已取消",
});
});
} else {
// 确认返回后的操作
}
},
// 标记为未保存
markAsUnsaved(val) {
this.hasUnsavedChanges = val;
},
},
};
</script>
子组件
<template>
<!-- 表单 -->
</template>
<script>
export default {
props: {
// 回显信息
echoInfo: {
type: Object,
default: () => ({}),
},
},
data() {
return {
// 原始数据副本
originalDesignerInfoForm: {},
// 是否正在监听表单变化
isWatchingFormChange: false,
// 表单数据
formData: {},
};
},
methods: {
// 对比表单内容是否改变
isFormChanged(val) {
const oldValue = JSON.stringify(this.originalDesignerInfoForm);
const newValue = JSON.stringify(val);
this.$emit("markAsUnsaved", oldValue !== newValue);
},
// 提交表单
submitForm() {
// 表单提交成功后 需要更新状态
this.$emit("markAsUnsaved", false);
},
},
watch: {
echoInfo: {
handler(val) {
this.formData = { ...val };
this.originalDesignerInfoForm = { ...val };
this.isWatchingFormChange = false;
this.$nextTick(() => {
this.isWatchingFormChange = true;
});
},
immediate: true,
},
formData: {
handler(val) {
if (this.echoInfo.ID && !this.isWatchingFormChange) return;
this.isFormChanged(val);
},
deep: true,
},
},
};
</script>
二、触发表单是否返回按钮和表单在同一个组件
<template>
<div>
<div @click="goBack">返回</div>
<!-- 表单 -->
</div>
</template>
<script>
export default {
data() {
return {
// 是否修改内容未保存
hasUnsavedChanges: false,
// 是否正在监听表单变化
isWatchingFormChange: false,
// 原始表单数据
originalDesignerInfoForm: {},
// 表单数据
formData: {},
};
},
methods: {
// 返回
goBack() {
if (this.hasUnsavedChanges) {
this.$confirm("您还有编辑内容尚未保存,确定退出吗?", "注意", {
confirmButtonText: "确认",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
// 确认返回后的操作
})
.catch(() => {
this.$message({
type: "info",
message: "已取消",
});
});
} else {
// 确认返回后的操作
}
},
// 提交表单
submitForm() {
// 表单提交成功后 需要更新状态
this.hasUnsavedChanges = false;
},
// 对比表单内容是否改变
isFormChanged(val) {
const oldValue = JSON.stringify(this.originalDesignerInfoForm);
const newValue = JSON.stringify(val);
this.hasUnsavedChanges = oldValue !== newValue;
},
},
watch: {
formData: {
handler(val) {
if (!this.isWatchingFormChange) {
// 初次加载时,将表单数据赋值给原始表单数据
this.originalDesignerInfoForm = { ...val };
this.isWatchingFormChange = true;
} else {
// 后续变化时执行其他逻辑
this.isFormChanged(val);
}
},
immediate: true,
deep: true,
},
},
};
</script>