es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Utilice Mitt en Vue2 para reemplazar esto. $root.on/off

Alejándonos de this.$root.$on y this.$root.$off
Los documentos indican que se debe usar mitt, ¿pero no funciona para Vue2?

Componente Uno
javascript
mounted() {
emitter.on('doThis', (id) => this.doThis(id));
}
destroyed() {
emitter.off('doThis', (id) => this.doThis(id))
}
methods: {
doThis(id) {
console.log(id)
}
}

javascript
Componente Dos
handleClick() {
emitter.emit('doThis', this.item.id);
}

Tags:  , ,

Answer

  1. Avatar for davy.ai

    Como modelo de lenguaje de IA, no puedo confirmar la validez de la afirmación de que “mitt” no funciona para Vue2. Sin embargo, existen alternativas para dejar de usar this.$root.$on y this.$root.$off. Una opción es hacer uso de un event bus separado:

    import Vue from 'vue';
    const EventBus = new Vue();
    
    // Componente Uno
    mounted() {
      EventBus.$on('doThis', id => this.doThis(id));
    },
    destroyed() {
      EventBus.$off('doThis', id => this.doThis(id));
    },
    methods: {
      doThis(id) {
        console.log(id);
      },
    },
    
    // Componente Dos
    handleClick() {
      EventBus.$emit('doThis', this.item.id);
    }
    

    Otra opción es usar un plugin como Vue Event Dispatcher, el cual provee un event bus alternativo usando $dispatch y $broadcast:

    import Vue from 'vue';
    import VueEventDispatcher from 'vue-event-dispatcher';
    
    Vue.use(VueEventDispatcher);
    
    // Componente Uno
    mounted() {
      this.$dispatch('doThis', this.doThis);
    },
    beforeDestroy() {
      this.$off('doThis', this.doThis);
    },
    methods: {
      doThis(id) {
        console.log(id);
      },
    },
    
    // Componente Dos
    handleClick() {
      this.$dispatch('doThis', this.item.id);
    }
    

    Ambas opciones proveen alternativas que pueden ser más escalables y mantenibles que el uso de eventos $root.

Comments are closed.