###### tags: `Vue` # Vue - 更靈活的使用 Life Cycle Hook 以往我們在 Vue 事件的監聽及註銷,可能會用一下方式實現。 ## 範例 ```javascript mounted() { window.addEventListener('event', this.fn) }, beforeDestroy() { window.removeEventListener('event', this.fn) }, methods: { fn() { // do something... } } ``` 而我們可以透過 Vue API 的 $once event 及 hook:beforeDestroy 將監聽和註銷事件集中在同一個function,改為以下寫法。 ## 範例 ```javascript mounted() { this.handleFn() }, methods: { handleFn() { window.addEventListener('event', this.fn) this.$once('hook:beforeDestroy', () => { // 只需監聽一次 hook:beforeDestroy,及註銷監聽 window.removeEventListener('event', this.fn) }) } fn() { // do something... } } ``` 而我們也能在父層監聽子層 Componet 的 Hook ## 範例 ```javascript <template> <div> // 監聽Componet hook update <ChildComponent @hook:update> </div> </template> ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up