Vue子组件调用父组件的方法

2019-11-28 11:00:35

Vue中子组件调用父组件的方法,这里有三种方法提供参考


下面有三种方法,我自己重点推荐第一种,毕竟这种简单粗暴好用好理解,不过这个有一个弊端,再组件嵌套组件的时候,尤其是用第三方组件里面调用自己的子组件的时候,其实已经是孙子组件了,这个时候就要parent.parent。。。。,这样就不好了,我们就得考虑其他方法了,具体怎么判断是父组件,还是爷爷组件,我会单独出一篇文章讲述。

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


父组件
<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</script>

子组件

<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$parent.fatherMethod();
      }
    }
  };
</script>


第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。

父组件

<template>
  <div>
    <child @fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</script>

子组件

<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$emit('fatherMethod');
      }
    }
  };
</script>


第三种是父组件把方法传入子组件中,在子组件里直接调用这个方法

父组件

<template>
  <div>
    <child :fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</script>

子组件

<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
    props: {
      fatherMethod: {
        type: Function,
        default: null
      }
    },
    methods: {
      childMethod() {
        if (this.fatherMethod) {
          this.fatherMethod();
        }
      }
    }
  };
</script>

三种都可以实现子组件调用父组件的方法,但是效率有所不同,根据实际需求选择合适的方法,嗯,就酱~


  • 2021-01-16 09:39:32

    iOS 更改状态栏、导航栏颜色,电池颜色

    注意事项,两种方法设置View controller-based status bar appearance 的值不一样,并且如果你的plist里面没有View controller-based status bar appearance,你需要新建一个。然后就可以成功了。

  • 2021-01-16 09:45:19

    tabbar的titlePositionAdjustment设置文字距离

    指定相应的数据去偏移一个位置,向右或者向下为正值,向左或者向上为负值,不过首先你得有一个相对位置的坐标。而tabbarItem文字的坐标是底部为x轴,y轴则是tabbarItem的centerX;

  • 2021-01-16 09:49:13

    Cocoapods如何查看项目中引入库的版本号

    项目中已经安装过Cocoapods,并生成了Podfile.lock文件。 打开终端,cd命令切换到项目中的Podfile.lock文件目录下,执行命令:cat Podfile.lock 即可。也可以用文本方式打开 Podfile.lock 文件。示例如下:

  • 2021-01-18 13:50:21

    vue实现粘贴功能

    paste事件就是粘贴事件 需要通过clipboardData获得粘贴的内容