vue.jsvuejs2vue-componentvue-events

Vue.js, emit multiple parameters from child to parent


I am trying to emit multiple parameters from child to parents. What is the best way to do it.

Child

 getUpdated(value, type) {
                  
    if (type === 'students') {
     this.students = value.map(val => val.id);
    }
                  
    if (type === 'programs') {
     this.programs = value.map(val => val.code);
    }
    this.$emit('selectedOptions', students:this.students, programs:this.programs );
    },

Parent

 onSelectedOption(students, programs) {
    if (students !== undefined || students.length > 1) {
      this.students = students;
  } 
  if (programs !== undefined || programs.length > 1) {
    this.programs = programs;
  }
},

Solution

  • Emit an object with multiple properties:

    this.$emit('selectedOptions', {
      students: this.students,
      programs: this.programs
    });
    

    And in the parent:

    onSelectedOption(options) {
      if (options.students && options.students.length) {
        this.students = options.students;
      } 
      if (options.programs && options.programs.length) {
        this.programs = options.programs;
      }
    },