实现Vue弹窗时,监听手机返回键关闭弹窗功能可以通过以下步骤完成:
<template>
<div>
<button @click="openModal">打开弹窗</button>
<div v-show="isModalOpen" @click.self="closeModal" @keydown.esc="closeModal">
<!-- 弹窗内容 -->
<p>这是一个弹窗</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isModalOpen: false
};
},
methods: {
openModal() {
this.isModalOpen = true;
},
closeModal() {
this.isModalOpen = false;
},
handleKeyPress(event) {
if (event.keyCode === 27) {
this.closeModal();
}
}
},
mounted() {
window.addEventListener('keydown', this.handleKeyPress);
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleKeyPress);
}
};
</script>
在上述代码中,我们在弹窗容器div
上绑定了两个事件:@click.self
和@keydown.esc
,分别用于关闭弹窗和监听手机返回键。当isModalOpen
为true
时,弹窗才会显示。
const closeModalMixin = {
methods: {
closeModal() {
this.isModalOpen = false;
},
handleKeyPress(event) {
if (event.keyCode === 27) {
this.closeModal();
}
}
},
mounted() {
window.addEventListener('keydown', this.handleKeyPress);
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleKeyPress);
}
};
export default {
name: 'Modal',
mixins: [closeModalMixin],
data() {
return {
isModalOpen: false
};
},
methods: {
openModal() {
this.isModalOpen = true;
}
},
template: `
<div>
<button @click="openModal">打开弹窗</button>
<div v-show="isModalOpen" @click.self="closeModal">
<!-- 弹窗内容 -->
<p>这是一个弹窗</p>
</div>
</div>
`
};
在以上代码中,我们将关闭弹窗和监听手机返回键关闭弹窗的代码抽离到了一个混入对象closeModalMixin
中,然后在弹窗组件中通过mixins
选项引入这个混入对象即可。这样做的好处是,无论页面中有多少个弹窗组件,我们都只需要在混入对象中实现一次代码即可。
示例说明:
下面是一个示例,如何在Vue中监听手机返回键关闭弹窗:
<template>
<div>
<button @click="openModal">打开弹窗</button>
<div v-show="isModalOpen" @click.self="closeModal" @keydown.esc="closeModal">
<!-- 弹窗内容 -->
<p>这是一个弹窗</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isModalOpen: false
};
},
methods: {
openModal() {
this.isModalOpen = true;
},
closeModal() {
this.isModalOpen = false;
},
handleKeyPress(event) {
if (event.keyCode === 27) {
this.closeModal();
}
}
},
mounted() {
window.addEventListener('keydown', this.handleKeyPress);
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleKeyPress);
}
};
</script>
另外一个示例,我们将关闭弹窗和监听手机返回键关闭弹窗的代码抽离到了一个混入对象中,让所有的弹窗组件都继承这个混入对象:
const closeModalMixin = {
methods: {
closeModal() {
this.isModalOpen = false;
},
handleKeyPress(event) {
if (event.keyCode === 27) {
this.closeModal();
}
}
},
mounted() {
window.addEventListener('keydown', this.handleKeyPress);
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleKeyPress);
}
};
export default {
name: 'Modal',
mixins: [closeModalMixin],
data() {
return {
isModalOpen: false
};
},
methods: {
openModal() {
this.isModalOpen = true;
}
},
template: `
<div>
<button @click="openModal">打开弹窗</button>
<div v-show="isModalOpen" @click.self="closeModal">
<!-- 弹窗内容 -->
<p>这是一个弹窗</p>
</div>
</div>
`
};
本文链接:http://task.lmcjl.com/news/10789.html