beforeMount() {
window.addEventListener('keydown', this.keyDown)
},
beforeDestroy() {
window.removeEventListener('keydown', this.keyDown)
},
methods: {
keyDown(e) {
if (e || window.e) {
const { key, target } = e
const deleteKeyArr = ['Backspace', 'Delete']
// 使用this.$el.querySelector('#efContainer')而不使用document.getElementById,是因为我们获取元素,尽量用this.$el去一级级获取,用document,单页面应用总会出些意外
// js的contains方法用来查看dom元素的包含关系-用来限定键盘事件只局限于当前dom范围内
const efContainerId = this.$el.querySelector('#efContainer')
if (deleteKeyArr.includes(key) && !this.delBtnDisabled && this.clickedBackSpace && target.contains(efContainerId)) {
this.deleteElement()
}
}
},