面试题答案
一键面试实现思路
- 自定义事件解绑:Vue 实例通过
$on
绑定的自定义事件,在组件销毁时需要通过$off
进行解绑。 - DOM 事件解绑:使用
addEventListener
绑定的 DOM 事件,在组件销毁时要调用removeEventListener
移除。 - 第三方库事件监听解绑:第三方库绑定的事件,需根据其提供的 API 来解绑事件监听。
关键代码片段
- 自定义事件解绑:
<template> <div></div> </template> <script> export default { created() { this.$on('customEvent', this.handleCustomEvent); }, methods: { handleCustomEvent() { // 处理逻辑 } }, beforeDestroy() { this.$off('customEvent', this.handleCustomEvent); } }; </script>
- DOM 事件解绑:
<template> <div ref="myDiv"></div> </template> <script> export default { mounted() { this.$refs.myDiv.addEventListener('click', this.handleClick); }, methods: { handleClick() { // 处理逻辑 } }, beforeDestroy() { this.$refs.myDiv.removeEventListener('click', this.handleClick); } }; </script>
- 第三方库事件监听解绑:
假设使用
lodash
的debounce
来处理一个事件监听,以模拟第三方库的情况。<template> <div></div> </template> <script> import _ from 'lodash'; export default { data() { return { debouncedFunc: null }; }, created() { this.debouncedFunc = _.debounce(this.handleEvent, 300); // 假设这里有一个元素触发这个防抖函数 document.addEventListener('scroll', this.debouncedFunc); }, methods: { handleEvent() { // 处理逻辑 } }, beforeDestroy() { document.removeEventListener('scroll', this.debouncedFunc); if (this.debouncedFunc) { this.debouncedFunc.cancel(); } } }; </script>