0

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.

  • as far as scope goes ... ion what respect? why calling `this.setter(70)` in parent successfully calls `setValue` in child with `this` being the child? .... probably some sort `.bind` going on in vue – Jaromanda X Jul 16 '22 at 05:08
  • `bind` is certainly used on methods when component instance is created, so they freely can be used as callbacks, otherwise you'd have this problem https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback . You can log a method and see that it's not the same function as you defined in `methods` – Estus Flask Jul 16 '22 at 06:19

0 Answers0