官方名字真是苦涩难懂,这个东西就是事件监听,监听一个事件,当事件触发时候就可以进行回调函数操作,逼格根本不高,贴点网上代码感受下:
1 2 3 4 5 6 7 | const timer = setInterval(() =>{ // 某些定时器操作 }, 500); // 通过$once来监听定时器,在beforeDestroy钩子可以被清除。 this.$once('hook:beforeDestroy', () => { clearInterval(timer); }) |
其实我想问beforeDestroy前面的hook干嘛的?似乎百度小伙伴都没疑问?就我好奇吗?难道是原生的生命周期监听就要这么搞?不懂,有知道的给我留言解释下
监听到生命周期函数beforeDestroy,也就是在组件销毁之前,回调函数就可以去清除上面定时器,$once、$on、$off的使用,这里送上官网的地址教程,在程序化的事件侦听器那里
再来个稍微复杂点的代码去感受下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>程序化的事件监听器</title> </head> <body> <div id="app"> <div v-if="isShow">嘻嘻嘻</div> <button @click="des">销毁</button> <button @click="show">点击</button> <div id="toast"></div> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.7/dist/vue.js"></script> <script> var Toast = Vue.extend({ template: '<div> <button @click="show">打印</button> </div>', created() { this.$on('print', () => { console.log('打印好东西,哈哈哈'); }); }, methods: { show() { this.$emit('print'); } } }); var toast = new Toast(); var vm = new Vue({ el: '#app', data: function() { return { isShow: true }; }, created() { this.$on('show', () => { console.log('嘻嘻嘻'); }); this.$once('hook:beforeDestroy', () => { toast.$destroy(); }); }, methods: { show() { this.$emit('show'); this.isShow = this.isShow ? false : true; if (!toast.$el) { toast.$mount('#toast'); } }, des() { vm.$destroy(); } }, destroyed() { console.log('实例已经销毁了'); } }); </script> </body> </html> |
最后再来认识下vue中的生命周期单词
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | beforeCreate: function(){ console.log(this); showData('创建vue实例前',this); }, created: function(){ showData('创建vue实例后',this); }, beforeMount:function(){ showData('挂载到dom前',this); }, mounted: function(){ showData('挂载到dom后',this); }, beforeUpdate:function(){ showData('数据变化更新前',this); }, updated:function(){ showData('数据变化更新后',this); }, beforeDestroy:function(){ vm.test ="3333"; showData('vue实例销毁前',this); }, destroyed:function(){ showData('vue实例销毁后',this); } |
7