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>

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


  • 2020-03-03 09:51:38

    写一个可插入自定义标签的 Textarea 组件

    为了实现这个功能,我最先想的是改造一个 <textarea> 然后我想到了 contenteditable (链接指向 mozilla.org) 这一属性 这是一个 html5 的属性,可以让元素内容可编辑

  • 2020-03-03 20:18:21

    Vuepress如何做到在 Markdown 中使用 Vue 语法

    在 vuepress 刚出时,我就觉得这是个很值得追更的开源项目。果不其然,里面众多的前端编程技巧让我受益良多。 于是在周末这种日子里,人家追剧我追码。 今天,我就和大家分享下 vuepress 是如何做到在 Markdown 中使用 Vue 语法的。

  • 2020-03-03 21:35:57

    PWA:安装 Web 应用

    要完整介绍 PWA 是什么,需要扯一堆名词,毫无意义。 以改造公羊阅读的过程为例,简要的说明什么是 PWA。

  • 2020-03-04 13:00:23

    NPM酷库:minimist,命令行参数解析

    昨天我们了解的dotenv库用于从文件中加载环境变量。环境变量用于程序运行时动态加载参数,除了环境变量,我们还可以在启动Node.js 程序时直接指定命令行参数: