Vue 子组件调用父组件方法总结

4,583 阅读1分钟

常用的方法总结下

  • $emit
  • $parent
  • prop
  • vuex(vuex代码比较麻烦,不写了,说下步骤吧 dispatch:actions=>commit:mutations)

$parent方法

父组件

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

子组件

<template>
  <div @click="activeBtn"> </div>
</template>
<script>
  export default {
    methods: {
      activeBtn() {
        this.$parent.fatherMethod()
      }
    }
  }
</script>

$emit方法

父组件

<template>
  <div>
    <child @callFather="activeSon"></child>
  </div>
</template>
<script>
  import child from '@/components/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('father组件');
      },
      activeSon(){
        this.fatherMethod()
      }
    }
  }
</script>

子组件

<template>
  <div @click="activeBtn"> </div>
</template>
<script>
  export default {
    methods: {
      activeBtn() {
        this.$emit("callFather")
      }
    }
  }
</script>

$prop方法

父组件

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

子组件

<template>
  <div @click="activeBtn"> </div>
</template>
<script>
  export default {
  props:{
    activeSon:  {
        type: Function,
        default: null
      }
  },
    methods: {
      activeBtn() {
        this.activeSon()
      }
    }
  }
</script>