Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
How does JavaScript (Vuejs) resolve scope in following scenario when $emit is used to send a handler from child to parent

So I was looking for ways to call a child component method from parent component without using refs to child and found an interesting solution.

var Child = {
  template: '<div>{{value}}</div>',
  data: function () {
    return {
      value: 0
    };
  },
  methods: {
    setValue(value) {
        this.value = value;
    }
  },
  created() {
    this.$emit('handler', this.setValue);
  }
}

new Vue({
  el: '#app',
  components: {
    'my-component': Child
  },
  methods: {
    setValueHandler(fn) {
        this.setter = fn
    },
    click() {
        this.setter(70)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>

<div id="app">
  <my-component @handler="setValueHandler"></my-component>
  <button @click="click">Click</button>  
</div>

As you can see this is a simple VueJS application where the OP is emitting a handler function from child to parent, so that when the parent calls this handler it updates the child state. However, I have a hard time understanding why this happens. In the solution above the child method setValue sets this.value, however when we call the emitted method in parent component shouldn't the parent look for the "value" field in parent scope, and not update "value" from child scope.

I didn't get a response from the OP, since this is an old post that I referred to. So would appreciate anyone who can help me understand this.

about 4 years ago · Santiago Gelvez
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda