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

Vue中子组件调用父组件的方法,这里有三种方法提供参考,第三种方式是将父组件的方法传到子组件,这不是很常用,就不记录了,原文https://www.cnblogs.com/jin-zhe/p/9523782.html

第一种方法是直接在子组件中通过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');
//附传参的话
this.$emit('fatherMethod', data);
      }
    }
  };
</script>
复制代码
posted @ 2020-06-19 22:15  君子笑而不语  阅读(856)  评论(0编辑  收藏  举报