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);
}
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
ythis.$root.$off
. Una opción es hacer uso de un event bus separado:Otra opción es usar un plugin como Vue Event Dispatcher, el cual provee un event bus alternativo usando
$dispatch
y$broadcast
:Ambas opciones proveen alternativas que pueden ser más escalables y mantenibles que el uso de eventos
$root
.