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

方式一

$parent
父组件

<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod(str) {
        console.log(str);
      }
    }
  };
</script>

子组件

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

方式二

props
父组件

<template>
  <div>
    <child :fatherMethod="fatherMethodOther"></child>
  </div>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethodOther(str) {
        console.log(str);
      }
    }
  };
</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('hello');
        }
      }
    }
  };
</script>

方式三

$emit
父组件

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

子组件

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

第一种不推荐,一般第三种。

网站导航

网站导航

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 您将在本文当中了解到,往网页中添加数据,从传统的dom操作过渡到数据层操作,实现同一个目标,两种不同的方式....
    itclanCoder阅读 25,883评论 1 12
  • 组件(Component)是Vue.js最核心的功能,也是整个架构设计最精彩的地方,当然也是最难掌握的。...
    六个周阅读 5,638评论 0 32
  • vue组件与组件通信有如下几种情况: 平行组件父组件与子组件子组件与父组件 它们之间通信有几种方法有: props...
    ch1n3h阅读 3,306评论 0 0
  • 夜读……人的一天,有 8 个小时都在工作,甚至有许多人一天工作十几个小时。我们对工作的感受,几乎成了我们对生活的全...
    Ronink阅读 263评论 0 0
  • 这几天小孩会考,比起在学校轻松了不少。心情也好很多,不时的嘴角上扬!我感觉心里也美美哒。今天是第一天考试,晚上放学...
    一凡娜娜阅读 223评论 0 5