Summary and examples of vue3 component communication methods

Summary and examples of vue3 component communication methods

The communication modes of vue3 components are as follows

  • props
  • $emit
  • $expose / ref
  • $attrs
  • v-model
  • provide / inject
  • Vuex
  • mitt

props

<child :msg2="msg2" />
<script setup>
    const props = defineProps({
        //Writing method 1 msg2:String
        //Writing method 2 msg2:{
            type:String,
            default:''
        }
    })
    console.log(props) // {msg2:'This is the information of the subcomponent 2'}
</script>

$emit

//Child.vue
<template>
    //Writing method 1 <div @click="emit('myclick')">button</div>
    //Writing method 2 <div @click="handleClick">button</div>
</template>
<script setup>
    // Method 1 const emit = defineEmits(['myClick'],['myClick2'])
    // Method 2 const handleClick = () => {
        emit('myClick','This is the information sent to the parent component');
     }
      
     // Method 2 is not applicable to vue3.2, the useContext() used has been abandoned import { useContext } from 'vue'
     const { emit } = useContext()
     const handleClick = () => { 
      emit('myClick','This is the information sent to the parent component'   
     }
</script>
 
// Parent.vue responds to <template>
    <child @myClick="onMyClick"></child>
</template>
<script setup>
    import child from "./child.vue"
    import onMychilk = (msg) => {
        console.log(msg) // Information received by the parent component}
</script>

expose / ref

The parent component obtains the properties of the child component or calls the child component method

<script setup>
    // Method 1: useContext() has been abandoned since vue3.2 import { useContext } from 'vue'
    const ctx = useContext()
    // Externally exposed properties and methods can be ctx.expose({
        childName: 'This is the property of the child component',
        someMethod(){
        console.log('This is the method of the child component')
        }
    })
</script>
 
// Parent.vue Note ref="comp"
<template>
    <child ref="comp"></child>
    <button @click="handleClick">Button</button>
</template>
<script>
    import child from './child.vue'
    import { ref } from 'vue' 
    const comp = ref(null)
    const handleClick = () => {
        console.log(comp.value.childName)
        comp.value.someMethod() //Call the method exposed by the subcomponent}
</script>

attts

attrs: contains a collection of non-props attributes of the parent scope except class and style

// Parent component <child :msg1="msg1" :msg2="msg2" title="3333"></child>
<script setup>
    import child from './child.vue'
    import { ref,reactive } from 'vue
    const msg1 = ref('111')
    const msg2 = ref('222')
</script>
 
// Subcomponent <script setup>
    import { defineProps,useContext,useAttars } from 'vue'
    const props = defineProps({
        msg1: String
    })
     
    // Method 1
    const ctx = useContext()
    console.log(ctx.attars) // {msg2:'222',title:'333'}
     
    // Method 2 
    const attrs = useAttrs()
    console.log(attars) // {msg2:'2222',title:'3333'}
</script>

v-model

Can support multiple data two-way binding

<child v-model:key="key" v-modle:value="value" />
<script>
    import child from './child.vue'
    import { ref,reactive } from 'vue'
    const key = ref('111')
    const value = ref('222')
</script>
 
//Subcomponent <template>
   <button @click="handleClick"></button>
</template>
<script setup>
    // Method 1 v3.2 has been removed import { useContext } from 'vue'
    const { emit } = useContext()
     
    // Method 2import { defineEmits } from 'vue'
    const emit = defineEmits(['key','value'])
     
    // Usage const handleClick = () => {
        emit('update:key','new key')
        emit('update:value','new value')
    }
</script>

provide / inject

provide/inject is dependency injection provide: allows us to specify the data we want to provide to descendant components inject: accepts the data we want to add to this component in any descendant component, no matter how deeply the component is nested

// Parent component <script setup>
    import { provide } from 'vue'
    const name = provide('name')
    console.log('name','Muhua')
</script>
//Subcomponent <script setup>
    import { inject } from 'vue'
    const name = inject('name')
    console.log(name) //Muhua</script>

Vuex

//store/index.js
import { createStore } from 'vuex'
export default createStore({
    state:{count:1},
    getters:{
        getCount:state=>state.count
    },
    mutations:
        add(state){
            state.count++
        }
    }
   })
 // main.js
 import { createApp } from 'vue'
 import APP from './App.vue'
 import store from './store'
 createApp(APP).use(store).mount("#app")
  
 // Use <template> directly
     <div>
         {{ $store.state.count }}
     </div>
     <button @click="$store.commit('add')">
     </button>
 </template>
  
 // Get <script setup>
     import { useStore,computed } from 'vuex'
     const store = useStore()
     console.log(store.state.count)
      
     const count = computed (()=>store.state.count)
     console.log(count)
 </script>

mitt

EventBus cross-component communication is no longer available in Vue3. The alternative is mitt.js, but the principle and method of EventBus are the same. The installation method is npm i mitt -S

Encapsulation

mitt.js
import mitt from 'mitt'
const mitt = mitt()
export default mitt

Use between components

// Component A 
<script setup>
    import mitt from './mitt'
    const handleClick = () => {
        mitt.emit('handleChange')
    }
</script>
// Component B 
<script setup>
import mitt from './mitt'
import { onUnmounted } from 'vue'
const someMethod = () => {...}
mitt.on('handleChange',someMethod)
onUnmounted(()=>{
    mitt.off('handleChange',someMethod)
})
</script>

This concludes this article on the summary and example usage of Vue3 component communication methods. For more information about the various methods of Vue3 component communication, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of non-parent-child component communication in Vue3
  • Details of 7 kinds of component communication in Vue3
  • Vue3.x uses mitt.js for component communication
  • Steps for Vue3 to use mitt for component communication

<<:  Detailed process of NTP server configuration under Linux

>>:  Explain the difference between iframe and frame in HTML with examples

Recommend

CSS3 analysis of the steps for making Douyin LOGO

"Tik Tok" is also very popular and is s...

Solution to the failure of loading dynamic library when Linux program is running

Unable to load dynamic library under Linux When t...

Summary of uncommon js operation operators

Table of contents 2. Comma operator 3. JavaScript...

How to solve the error of PyCurl under Linux

Solution to "Could not run curl-config"...

Detailed explanation of the solution to font blur when using transform in CSS3

This question is very strange, so I will go strai...

CSS border adds four corners implementation code

1.html <div class="loginbody"> &l...

Detailed explanation of asynchronous programming knowledge points in nodejs

Introduction Because JavaScript is single-threade...

JavaScript to implement login slider verification

This article example shares the specific code of ...

How to create a MySQL master-slave database using Docker on MacOS

1. Pull the MySQL image Get the latest MySQL imag...

Detailed tutorial on installing centos8 on VMware

CentOS official website address https://www.cento...