better way to handle multiple emits in vue

Viewed 1045

I have emits to do if I enter a page to do some magic with a menu, I have a solution but its seems very static and too much code for such fancy modern things like vue or quasar.

On every component I need to emit a event I use this for example:

this.$root.$emit('category-one--name')

And to receive the emit event and handle stuff I use this:

this.$root.$on('category-one--name', this.setSelectBox1)
this.$root.$on('category-otherone--name', this.setSelect2)
this.$root.$on('category-more--name', this.setSelectBox3)
this.$root.$on('category-somemore--name', this.setSelect4)
this.$root.$on('category-ansoson--name', this.setSelectBox5)

then I handle stuff with the following:

setSelectBox1() {
  this.model = this.categories[1]
},
setSelectBox2() {
  this.model = this.categories[2]
},

Is there a better way, for example give the emitted event an Id or something and then to iterate over all in one method and not just to repeat the code?

thanks

1 Answers

Emit function accept a value as second param so try this:

this.$root.$emit('category-change', this.name);

Then:

this.$root.$on('category-change', this.setSelectBox);


setSelectBox(category) {
  // set model here
},
Related