首页 > web前端 > Vue.js > 正文

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

青灯夜游
发布: 2021-10-26 12:03:28
原创
124339 人浏览过

方法:1、子组件中通过“this.$parent.event”来调用父组件的方法。2、子组件用“$emit”向父组件触发一个事件,父组件监听这个事件即可。3、父组件把方法传入子组件中,在子组件里直接调用这个方法即可。

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

本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。

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

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

父组件

<template>
  <p>
    <child></child>
  </p>
</template>
<script>
  import child from &#39;~/components/dam/child&#39;;
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log(&#39;测试&#39;);
      }
    }
  };
</script>
登录后复制

子组件

<template>
  <p>
    <button @click="childMethod()">点击</button>
  </p>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$parent.fatherMethod();
      }
    }
  };
</script>
登录后复制

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

父组件

<template>
  <p>
    <child @fatherMethod="fatherMethod"></child>
  </p>
</template>
<script>
  import child from &#39;~/components/dam/child&#39;;
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log(&#39;测试&#39;);
      }
    }
  };
</script>
登录后复制

子组件

<template>
  <p>
    <button @click="childMethod()">点击</button>
  </p>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$emit(&#39;fatherMethod&#39;);
      }
    }
  };
</script>
登录后复制

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

父组件

<template>
  <p>
    <child :fatherMethod="fatherMethod"></child>
  </p>
</template>
<script>
  import child from &#39;~/components/dam/child&#39;;
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log(&#39;测试&#39;);
      }
    }
  };
</script>
登录后复制

子组件

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

【相关推荐:vue.js教程

以上是vue子组件怎么调用父组件的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!