第66号vue面试题---程序化的事件监听器

738 阅读1分钟

一.什么是程序化的事件监听器?

一问三不知....

二.举例说明?

这个我擅长,比如我现在有一个vue实例vm,并且我现在还要销毁它。
大家都知道,销毁一个vue实例调用$destroy方法,销毁后,vm的所有指令与监听的事件就通通没了。
但是问题来了,我们在操作该vm的过程中,又手动挂载了其他vue实例比如toast。
if(!toast.$el){
        toast.$mount('#toast');
}
导致该vm销毁了,但是toast没有,toast的指令和监听的事件依旧能触发。
所以这个时候就要用到我们的程序化事件监听器啦,
this.$once('hook:beforeDestroy',()=>{
                toast.$destroy();
          })

我们需要监听vm在即将销毁时需要执行的生命周期函数beforeDestroy,在它执行时,销毁toast实例。

三.口说无凭,上代码

<!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>Document</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="js/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>

四.代码没注释

你没有看错,真的没有注释QAQ。。。