Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!