法一:直接在子组件中通过this.$parent.event来调用父组件的方法

// 父组件
<template><div><child></child></div></template>
<script>
  ...
    methods: {
      fatherMethod() {
        console.log('被子调动');
      }
    }
  ...
</script>


//子组件
<template>
  ...
</template>
<script>
 ...
    methods: {
      childMethod() {
        this.$parent.fatherMethod();
      }
    }
...
</script>

法二:在子组件里用$emit向父组件触发一个事件,父组件监听这个事件

// 父组件
<template>
  <div>
    <child @fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  ...
    methods: {
      fatherMethod() {
        console.log('被子调用');
      }
    }
 ...
</script>

//子组件
<template>
  ...
</template>
<script>
  ...
    methods: {
      childMethod() {
        this.$emit('fatherMethod');
      }
    }
 ...
</script>

法三:父组件把方法传入子组件中,在子组件里再调用这个方法

// 父组件
<template>
  <div>
    <child :fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
 ...
    methods: {
      fatherMethod() {
        console.log('测试');
      }
    }
  ...
</script>

//子组件
<template>
 ...
</template>
<script>
  export default {
    props: {
      fatherMethod: {
        type: Function,
        default: null
      }
    },
    methods: {
      childMethod() {
        if (this.fatherMethod) {
          this.fatherMethod();
        }
      }
    }
  };
</script>

tip:

推荐使用第二种方式,简洁

第一种方法经常性会出现找到的父级并不是我们想要的父级,this.$parent可以调用父组件自定义的方法。但是在使用UI组件时可能会出现无法使用this.$parent直接调用父组件方法的问题,如 iview element等

 

Logo

前往低代码交流专区

更多推荐