Vue sibling components how to exchange event methods, without vuex, read a lot on the Internet, is an example, do not quite understand?

clipboard.png
graphic CAPTCHA and SMS CAPTCHA are both a component. Click to get the SMS CAPTCHA and then call the method in the graphic CAPTCHA component to refresh the image

.
May.22,2022

component description:
parent component: a graphic verification code B SMS verification code C

idea:
use parent component A to operate events (ref) of B, and the event flow is as follows: C-> A-> B

approximate code:

component A

<template>
    <B ref="children"/>
    <C :triggerChildMehtod="triggerChildMehtod"/>
</template>
<script>
export default {
  methods: {
     triggerChildMehtod(){
        // 
        this.$refs.children.refresh();
     }
  }
}
</script>

component B

<template>
    <div>somecode...</div>
</template>
<script>
export default {
  methods: {
     refresh(){
        // somecode
     }
  }
}
</script>

component C

<template>
    <div>somecode...</div>
</template>
<script>
export default {
  props: ['triggerChildMehtod'],
  methods: {
     refresh(){
        // 
        this.triggerChildMehtod()
     }
  }
}
</script>

Click to get the SMS verification code and send $emit to the parent component. The parent component's method updates the change value (iPP is also fine). This change is transmitted to the graphic CAPTCHA component (props). If you hear a change in the received value in the graphical CAPTCHA component, you can perform the image refresh method


by adding an observable object to the SMS CAPTCHA component. Subscribe to the graphic CAPTCHA component, click to get the SMS CAPTCHA, then push the update, and then the graphic CAPTCHA component receives the push refresh image.


you can also use vue's message mechanism. Create a new vue object to manage messages.
Click to get the CAPTCHA, then the item graphic CAPTCHA component sends a refresh message, and the graphical CAPTCHA component receives the message and refreshes it.

// msg
var msg = new Vue();
// 
msg.$emit('pic_verify',{refresh:true});

// pic_verify
msg.on('pic_verify',(data)+>{
    if(data.refresh) {
        // 
        ...
    }
});
Menu