16

Vue.js 截获 Ctrl+S 组合键以及自动保存(提交)功能的实现

 3 years ago
source link: https://rollingstarky.github.io/2020/12/14/vue-js-add-auto-save-and-ctrl-s/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Vue.js 截获 Ctrl+S 组合键以及自动保存(提交)功能的实现

发表于 2020-12-14

| 分类于 JavaScript

| 0

| 阅读次数: 3

字数统计: 1.1k

|

阅读时长 ≈ 0:01

默认情况下,Chrome 中按下 Ctrl+S 组合键会进入“保存网页”界面,并不会与网页中的具体内容做交互。

最近在做一个前端基于 Vue 的在线文档,希望网页中按下 Ctrl+S 组合件就能触发提交动作,将前端数据的改动存储到后端数据库中。
并且不管用户是否操作,每隔特定时间也会自动提交文档的当前内容到后端,实现自动保存的功能。

示例代码如下:

<template>
<button @click="save('button')">保存</button>
</template>

<script>

export default {
mounted() {
document.addEventListener('keydown', this.saveContent)

this.timer = setInterval(() => {
this.save('timer')
}, 10 * 1000)
},

beforeDestroy() {
document.removeEventListener('keydown', this.saveContent)
clearInterval(this.timer)
},

methods: {
save(type) {
console.log(`content saved by ${type}`)
},
saveContent(e) {
var key = window.event.keyCode ? window.event.keyCode : window.event.which
if (key === 83 && e.ctrlKey) {
this.save('hot key')
e.preventDefault()
}
}
}
}
</script>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK