需求
通过 Canvas 绘制的图形数据要实现即时保存,但又不能太过频繁地调用接口保存数据至后台。可以在图形数据发生改动后把数据先保存到本地,再通过监听页面关闭或刷新保存至后台。
实现
1. 在 watch 中深度监听图形属性的改变
watch: {
activeShape: {
// 此处注意,handler 函数不能为箭头函数,this 会取上下文,而不是组件里的 this,此外,深度监听,必须为 handler 函数名,否则会无效果
handler: function (newVal, oldVal) {
setTimeout(() => {
// 如果在 1s 中之内用户没有改变任何对象的任何属性,则保存数据至本地
this.saveToLocal();
}, 1000);
},
// deep 设置为 true 的意思是修改 activeShape 中任何一个属性,都会执行handler这个方法
deep: true
}
}
2. 通过 unload 和 beforeunload 事件监听页面关闭或刷新,同步本地数据至后台
unload
和 beforeunload
事件是在窗口卸载的时候触发的,可以在用户刷新或关闭窗口的时候处理一些逻辑,想要在事件中通过控制台打印调试或者提示用户是不可行的,可以在事件中添加 debugger,窗口关闭的时候能跟进断点,但是刷新的时候断点也会被忽略,但是我们不需要调试,直接起飞:
mounted() {
window.addEventListener("beforeunload", e => this.beforeunloadHandler(e));
window.addEventListener("unload", e => this.unloadHandler(e));
},
destroyed() {
window.removeEventListener("beforeunload", e => this.beforeunloadHandler(e));
window.removeEventListener("unload", e => this.unloadHandler(e));
},
methods: {
beforeunloadHandler() {
this._beforeUnload_time = new Date().getTime();
},
unloadHandler(e) {
this._gap_time = new Date().getTime() - this._beforeUnload_time;
debugger
// 关闭或刷新窗口都保存数据到后台
this.saveToCloud();
// 判断窗口是关闭还是刷新
if (this._gap_time <= 5) {
// TODO:
}
},
}
参考代码:https://blog.csdn.net/asd577007722/article/details/118673459