vue中子組件調用父組件的方法

1.子組件通過this.$parent.event來調用父組件的方法
父組件

<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod(str) {
        console.log(str);
      }
    }
  };
</script>

子組件

<template>
  <div>
    <button @click="childMethod">點擊</button>
  </div>
</template>
<script>
  export default {
     methods: {
        childMethod(){
           this.$parent.fatherMethod('hello');
        }
     }
  };
</script>  

2.子組件裏用$emit向父組件觸發一個事件,父組件監聽即可
父組件

<template>
  <div>
    <child @fatherMethod="fatherMethodOther"></child>
  </div>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethodOther(str) {
        console.log(str);
      }
    }
  };
</script>

子組件

<template>
  <div>
    <button @click="childMethod">點擊</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$emit('fatherMethod', 'hello');
      }
    }
  };
</script>

3.父組件將這個方法傳入子組件,在子組件中直接調用
父組件

<template>
  <div>
    <child :fatherMethod="fatherMethodOther"></child>
  </div>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethodOther(str) {
        console.log(str);
      }
    }
  };
</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('hello');
        }
      }
    }
  };
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章