vue组件传递函数

2,715 阅读1分钟

组件传递函数

// 父组件
<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: '我是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>
// 子组件
<template>
  <div>
    <button @click="handClick(count)">点击加 {{ count }}</button>
  </div>
</template>
<script>
export default {
  name: 'B',
  data () {
    return {
      count: 1,
    }
  },
  props: {
    add: {
      type: Function
    }
  },
  methods: {
    handClick () {
      console.log('child this=====', this);
      // 这里调用父组件传递过来的方法add;虽然调用此方法的this是子组件的,但是add方法内部的this还是父组件的,因为在传递函数时vue帮我们做了this绑定。具体可以查看方法的"BoundThis"这个属性
      this.add(this.count); 
    }
  },
}
</script>

看图解析

结论

vue中的方法都有BoundThis这个属性,如果方法是本组件的,那么这个属性会指向本组件实例本身;如果vue中的方法是从外部传入的,那么方法内部的BoundThis属性绑定的是外部组件实例。

这点和react不一样,react传递函数时需要手动绑定this;但是在vue中传递函数时,vue帮我们自动绑定好了。