2023年11月20日 星期一

vue2 event hook destroyed

在官方建議寫法一般是這樣

mounted() {
this.$root.$on("getSelf", this.getSelf)
},
destroyed() {
this.$root.$off("getSelf")
},

但你也可以這樣寫

mounted() {
this.$root.$on("getSelf", this.getSelf)
this.$on("hook:destroyed", () => this.$root.$off("getSelf"))
},

這樣寫有什麼好處呢,主要防止邏輯四散,每個人寫作習慣不同,mounted跟destroyed不一定就在旁邊,有人mounted會寫一大串,最造成閱讀上沒這麼直覺。你可以在宣告偵聽時就確定他會在component destroyed時被取消偵聽減少資源浪費。這寫法就跟golang的defer類似。

其實早在很久前就有這樣寫了,只是沒記下來真的會忘記,到最近又碰到vue想要寫才把這招翻出來,所以就做個紀錄