vue 子组件调用父组件方法

有三种方法:

  1. this.$parent.fatherMethod();直接通过$parent调用父组件方法。
  2. 子组件用$emit向父组件出发一个事件,父组件监听该事件。
       childMethod() {
       // 子组件
         this.$emit('fatherMethod');
      }
    
      // 父组件
      <child @fatherMethod="fatherMethod"></child>
    
  3. 父组件将方法传入子组件,子组件调用即可。
       childMethod() {
       // 子组件
         this.$emit('fatherMethod');
      }
    
      // 父组件
      <child :fatherMethod="fatherMethod"></child>
    
      props: {
        fatherMethod: {
          type: Function,
          default: null
        }
      },
      methods: {
        childMethod() {
          if (this.fatherMethod) {
            this.fatherMethod();
          }
        }
      }
    
posted @ 2021-06-10 16:08  lambertlt  阅读(326)  评论(0编辑  收藏  举报