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

11 Reasons Why Bootstrap Is So Popular

Preface Bootstrap, the most popular front-end dev...

Record a slow query event caused by a misjudgment of the online MySQL optimizer

Preface: I received crazy slow query and request ...

Detailed tutorial on installing MySQL 8 in CentOS 7

Prepare Environmental information for this articl...

How to modify port 3389 of Windows server 2008 R2 remote desktop

The default port number of the Windows server rem...

Linux echo text processing command usage and examples

The description of echo in the Linux help documen...

Nginx installation error solution

1. Unzip nginx-1.8.1.tar.gz 2. Unzip fastdfs-ngin...

MYSQL slow query and log example explanation

1. Introduction By enabling the slow query log, M...

Detailed explanation of CSS multiple three-column adaptive layout implementation

Preface In order to follow the conventional WEB l...

Some common mistakes with MySQL null

According to null-values, the value of null in My...

How to use mqtt in uniapp project

Table of contents 1. Reference plugins in the uni...

Commonplace talk about the usage of MYSQL pattern matching REGEXP and like

like LIKE requires the entire data to match, whil...

How to use rem adaptation in Vue

1. Development environment vue 2. Computer system...