我在mounted組件的生命周期中定義了 2 個事件偵聽器,允許用戶v-dialog通過在外部雙擊或按退出鍵來關閉 a。撰寫這些原始事件監聽器是我所知道的實作我想要的功能的唯一方法。是這樣的:
<template>
<v-container>
<v-dialog :value="value" max-width="55vw" height="70vw" persistent>
...some stuff...
</v-dialog>
</v-container>
</template>
<script>
export default {
name: "a name",
props: {
value: { required: true },
},
mounted() {
let that = this;
document.addEventListener("keyup", function (evt) {
if (evt.key === "Escape") {
that.closeDialog();
}
});
document.addEventListener("dblclick", function (e) {
if (e.target == document.getElementsByClassName("v-overlay__scrim")[0]) {
that.closeDialog();
}
});
},
unmounted() {
window.removeEventListener("keyup");
window.removeEventListener("dblclick");
},
methods: {
closeDialog() {
this.$emit("input");
},
},
};
</script>
我想將關閉 v-dialogs 的功能擴展到其他幾個組件,但是將這些事件偵聽器添加到多個組件的mounted塊似乎是多余的。有沒有更好的方法來實作這一目標?
uj5u.com熱心網友回復:
在我看來,您不應該在這種情況下使用本機事件。此外,在特定 Vue 組件的檔案上添加事件監聽器可能會導致混淆,因為您總是在任何地方監聽該事件(在您的情況下,“esc”鍵被按下)。想象一下,如果您有大量組件,當您按下“esc”時,一些代碼正在執行。如果您不是這段代碼的作者,則“很難”分辨出它的來源。
對于這種情況,我建議:使用可以包含生命周期掛鉤的 Mixin(vue 2)或使用可組合項來匯入函式(vue 2 with vue/composition-api 或 vue 3)并使用適當的生命周期掛鉤手動注冊它功能。
順便說一句,在您的代碼中,在洗掉事件偵聽器部分,您應該傳遞函式參考。所以最好將方法提取到該組件的適當 vue 方法中。
mounted() {
let that = this;
document.addEventListener("keyup", this.close);
document.addEventListener("dblclick", this.close2);
},
unmounted() {
window.removeEventListener("keyup", this.close);
window.removeEventListener("dblclick", this.close2);
},
methods: {
close(evt) {
if (evt.key === "Escape") {
this.$emit("input");
}
},
close2(e) {
if (e.target == document.getElementsByClassName("v-overlay__scrim")[0]) {
this.$emit("input");
}
},
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535590.html
