Vue3 parent-child component communication, parent-child parameter passing
foreword
The friends of Vue2 should have experienced the madness in the process of switching to Vue3. Many places are used differently. In this issue, I will tell you about the problem of parent-child component communication that I also encountered in the development of vue3 recently.
father to son
Introduce the son.vue subcomponent in the parent component , and pass the value msg to the subcomponent
The following figure is the parent component
<template>
<div class="father">
<div>我是父级</div>
<Son :msg="msg" />
</div>
</template>
<script setup lang="ts">
import {
ref } from 'vue';
import Son from './son.vue';
const msg = ref('我是父级传的值');
</script>
<style scoped>
.father {
margin-top: 100px;
text-align: center;
font-size: 26px;
}
</style>
After the parent passes the value, the child component uses defineProps to receive the value of the msg passed by the parent .
The following figure is the subcomponent
<template>
<div>
<div>我是子级</div>
<div>子级接受:{
{
msg }}</div>
</div>
</template>
<script setup lang="ts">
interface Props {
msg: String;
}
defineProps<Props>();
</script>
<style scoped></style>
Effect diagram
At the end of the child component, pass the value of the parent component.
child's father
Use defineEmits to register a custom event, then trigger emit, and pass the event to the parent component
Subassembly
<template>
<div>
<div>我是子级</div>
<el-button type="primary" size="default" @click="byValue"
>向父组件传值</el-button
>
</div>
</template>
<script setup lang="ts">
import {
ref } from 'vue';
const sonValue = ref('我是子级传的值');
const emit = defineEmits(['sonValue']);
const byValue = () => {
console.log('向父组件传值');
emit('sonValue', sonValue.value);
};
</script>
<style scoped></style>
The sonValue event passed from the child component is bound to the parent component and received using the getValue method.
parent component
<template>
<div class="father">
<div>我是父级</div>
<Son @sonValue="getValue" />
<div>我是子级传值:{
{
SonValue }}</div>
</div>
</template>
<script setup lang="ts">
import {
ref } from 'vue';
import Son from './son.vue';
const SonValue = ref<String>('');
const getValue = (val: String) => {
console.log('接收子组件', val);
SonValue.value = val;
};
</script>
<style scoped>
.father {
margin-top: 100px;
text-align: center;
font-size: 26px;
}
</style>
before passing
after passing
Summarize
Recently, writing projects with Vue3 has also stepped on a lot of pitfalls. Many places use vue2 differently. There are also small partners who have switched from Vue2 to Vue3 to discuss and discuss together.