vue之子组件访问父组件的方法

假设这是父组件 father

<template>
  <div>
    <Child />
  </div>
</template>

<script>
import Child from './child'
export default {
  components:{ Child },
  data() {
    return {
    };
  },
  methods: {
    print(){
      console.log(123);
    }
  },
};
</script>

在father中定义了一个print方法打印123

我想在子组件中调用这个print方法,需要怎么做呢,有这几种方式:

  • 1.通过实例上的$father访问
    子组件 child
mounted(){
  this.$father.print()   // ==>  123
}
  • 2.通过组件传值 props
    father组件
  <Child :fatherPrint="print" />

child组件

props:{
  fatherPrint: Function
}
mounted(){
  this.fatherPrint()
}

  • 3.通过$emit向父组件触发一个事件,然后父组件调用
    child组件
  mounted(){
    this.$emit("printEmit")
  }

father组件

  <Child @printEmit="print" />
posted @ 2021-02-23 15:03  zoo-x  阅读(203)  评论(0)    收藏  举报