Vue3父子组件通信,父子传参
前言
Vue2的小伙伴应该该经历过转战Vue3过程的中的抓狂。好多地方使用都不太一样,这期就给大家讲一下近期我也在用vue3开发中遇到到的问题父子组件通信。
父传子
在父组件中引入son.vue子组件,为子组件传值msg
下图是父组件
<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>
在父级传值之后,子组件使用defineProps来接收父级传过来msg的值。
下图是子组件
<template>
<div>
<div>我是子级</div>
<div>子级接受:{
{
msg }}</div>
</div>
</template>
<script setup lang="ts">
interface Props {
msg: String;
}
defineProps<Props>();
</script>
<style scoped></style>
效果图
在子组件可以结束到了,父组件的传值。
子传父
使用defineEmits注册一个自定义事件,然后触发emit,向父组件传递事件
子组件
<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>
通过子组件传过来的sonValue事件,绑定到父组件中,使用getValue方法接收。
父组件
<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>
传之前
传值后
总结
最近用Vue3写项目也踩了很多的坑,很多地方使用vue2都不太一样,同样有Vue2转战Vue3的小伙伴可以一起讨论讨论。