Rumah  >  Artikel  >  hujung hadapan web  >  vue子组件怎么调用父组件的方法

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

青灯夜游
青灯夜游asal
2021-10-26 12:03:28124342semak imbas

方法: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教程

Atas ialah kandungan terperinci vue子组件怎么调用父组件的方法. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:vue组件是什么Artikel seterusnya:vue兼容ie几