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

vue子组件调用父组件的函数的方法还有超简单的写法,我也是最近在VUE模块化开发时在网上寻找的方法,下面给大家列出了三种不同的写法,都可以完美的实现子组件调用父组件内的函数,曾经我一直使...

vue子组件调用父组件的函数的方法还有超简单的写法,我也是最近在VUE模块化开发时在网上寻找的方法,下面给大家列出了三种不同的写法,都可以完美的实现子组件调用父组件内的函数,曾经我一直使用下面的第二种方法,虽然写法很规范,但稍微有些复杂,所以找了更简单的方法分享给大家。

第一种方法是直接在子组件中通过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>

 

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

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
admin
admin

651 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章