方法一:子组件$emit触发父组件事件

   @click= "triggerBrotherMethods"
 
   triggerBrotherMethods() {
    this.$emit( 'clickBrotherBtn')
   },

<template>
  <div>
   <son @clickBrotherBtn= "triggerBrotherMethods"></son2>
  </div>
</template>

<script>
// 引入子组件一
import son from './son'

 
export default {
  data() {
   return { }
  },
  // 注册子组件
  components: {
   son
  },
  methods: {
   triggerBrotherMethods() {
    console.log("父组件的方法")
   },
  }
}
</script>

方法二:子组件访问父组件的方法,那么将函数直接作为 props 传递

//父组件
<template>
  <ChildComponent :getFatherMethod="parentMethod" />
</template>

export default {
  methods: {
    parentMethod() {
      console.log("父组件的方法")
    }
  }
}
 
// 子组件
export default {
  props: {
    getFatherMethod: {
      type: Function,
      default: () => {
        return Function
      }
    }
  },
  mounted() {
    // 调用父组件的方法
    this.getFatherMethod();
  }
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐