Component transfer function

/ / the parent component
<template>
  <div>
    <B :add="childrenClick"></B>
    <p>{{ countF }}</p>
  </div>
</template>

<script>
import B from './B'
export default {
  name: 'A',
  data () {
    return {
      countF: 0.msg: 'I'm component A'}},methods: {
    childrenClick (c) {
      console.log('parent this====='.this);
      this.countF += c;
      console.log('this.countF==='.this.countF);
      console.log('this.msg==='.this.msg); }},components: {
    B,
  }
}
</script>
Copy the code
/ / child component
<template>
  <div>
    <button @click="handClick(count)">Click add {{count}}</button>
  </div>
</template>
<script>
export default {
  name: 'B',
  data () {
    return {
      count: 1,}},props: {
    add: {
      type: Function}},methods: {
    handClick () {
      console.log('child this====='.this);
      // Call the method add; Although the this that calls this is the child, the this inside the Add method is the parent, because Vue did the this binding for us when we passed the function. Look at the "BoundThis" property of the method
      this.add(this.count); }}},</script>
Copy the code

Look at the picture.

conclusion

All methods in vUE have BoundThis. If the method belongs to the component, this property points to the component instance itself. If the method in the VUE is passed in from outside, the BoundThis property inside the method is bound to the external component instance.

Unlike React, react passes functions that bind this manually; But when passing functions in VUE, VUE automatically binds them for us.