【Vue/React】关于Vue中父子组件相互调用其方法

一、父组件使用子组件的方法

子组件 children.vue
子组件: 在子组件中定义好给父级调用的方法即可 childMethod()

<template>
  <div>我是子组件Children</div>
</template>

<script>
  export default {
    data(){
      return {
        age: 0
      }
    },
    methods:{
      childMethod() {
        this.age += 1
      }
    }
  }
</script>

父组件 parent.vue

父组件: 在子组件中加上ref即可通过 this.$refs.ref.method 调用

<template>
  <div @click="parentMethod">
    <children ref="child"></children>
  </div>
</template>

<script>
  import children from 'components/children/children.vue'
  export default {
    data(){
      return {
      }
    },
    components: {      
      'children': children
    },
    methods:{
      parentMethod() {
        this.$refs.child.childMethod(); 
      }
    }
  }
</script>

二、子组件使用父组件的方法

子组件 children.vue

子组件:通过 this.$emit 对外触发show方法,可携带参数

<template>
  <div>
    <h1>子组件</h1>
    <Button @click="sonClick">触发父组件方法</Button>
  </div>
</template>
 
<script>
export default {
  data () {
    return {
      sonMessage: '子组件数据sonMessage',
      sonData: '子组件数据sonData'
    };
  },
  methods: {
    sonClick () {
      this.$emit('show', this.sonMessage, this.sonData);
    }
  }
}
</script>

父组件 parent.vue

父组件:在子组件中监听子组件的方法 @show

<template>
  <div>
    <h1>父组件</h1>
    <children @show="showFather"></children>
  </div>
</template>
 
<script>
import children from 'components/children/children.vue'
export default {
  data () {
    return {
    }
  },
  methods: {
    showFather (a, b) {
      console.log('触发了父组件的方法:' + a + '---' + b);
    }
  }
}
</script> 
发布了134 篇原创文章 · 获赞 80 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Umbrella_Um/article/details/104508342