Vue系列---【子组件调用父组件的方法】

Vue中子组件调用父组件的方法,三种方法

  • 第一种方法是在子组件中通过this.parent.eventparent)

父组件:

复制代码
<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from '~/components/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.$parent.fatherMethod();多试几层
        this.$parent.fatherMethod();
      }
    }
  };
</script>
复制代码
  • 第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件(Vue推荐使用)。

父组件:

复制代码
<template>
  <div>
    <child @fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from '~/components/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod(val) {
        console.log('val实际就是子组件传过来的childParam');
      }
    }
  };
</script>
复制代码

子组件:

复制代码
<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
  data(){
    return {
    childParam:{}
    }
  }, methods: { childMethod() {
this.$emit('fatherMethod',this.childParam); } } }; </script>
复制代码
  • 第三种是父组件把方法传入子组件中,在子组件里直接调用这个方法

父组件:

复制代码
<template>
  <div>
    <child :fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from '~/components/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('父组件方法');
      }
    }
  };
</script>
复制代码

子组件:

复制代码
<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        if (this.fatherMethod) {
          this.fatherMethod();
        }
      }
    }
  };
</script>
复制代码

posted on   少年攻城狮  阅读(1931)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2021-04-26 java基础---【数据结构可视化工具,包含红黑树,二叉树等演示工具】
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示