富文本每30秒保存一次(根据内容修改来调动接口)
需求:监听富文本内容的变化, 有改变就触发事件
方法:采用节流来控制定时器
1. 首先封装一个 throttle.js
export function throttle(fn, delay) {
//节流
let canRun = true; // 通过闭包保存一个标记
return function() {
if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return
canRun = false; // 立即设置为false
setTimeout(() => {
// 将外部传入的函数的执行放在setTimeout中
fn.call(this);
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉
canRun = true;
}, delay);
};
}
- 引入到页面中
import { throttle } from "../../util/throttle";
export default:{
watch: {
msg: {
handler: throttle(function () {
let temp = `<body>${this.msg}</body>`;
this.$post(this.api.saveRecord, {
content: temp,
id: this.caseSchedulingId,
}).then((res) => {
if (res.code == 200) {
this.$message.success("保存成功!");
}
});
}, 30000),
},
},
}