[Vue / React] About Vue father and son in another component calls its methods

A parent component method using the sub-assembly

Subassemblies children.vue
subcomponents: a good method to define the parent calls in the sub-assembly can bechildMethod()

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

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

Parent component parent.vue

Parent component: add ref in the sub-assembly can by this.$refs.ref.methodcalling

<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>

Second, the use of the subassembly assembly method of the parent

Subassemblies children.vue

Subcomponents: by this.$emitthe external trigger show method, may carry parameters

<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 component parent.vue

Methods monitor subcomponents in the sub-components: parent component @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> 
Published 134 original articles · won praise 80 · views 30000 +

Guess you like

Origin blog.csdn.net/Umbrella_Um/article/details/104508342