vue3中实现组件通信方式总结
1、基础的父子通信—父传子
父组件通过属性绑定传值,子组件通过defineProps接收
父组件可以传递具体的值,也可以传递变量
子组件接受可以通过数组的方式,或对象的方式接收
示例demo:
父组件:
<template>
<div class="box">
<!-- 2、使用组件,并传值【message传的是字符串,num传递的是变量】 -->
<Child message="父组件传给子组件的一段文本值" :num="num"></Child>
</div>
</template>
<script setup lang="ts">
// 1、引入子组件
import Child from './Child.vue'
import {
ref} from 'vue'
const num = ref(100)
</script>
<style scoped>
.box {
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 400px;
background: rgb(248, 255, 233);
}
</style>
子组件Child
<template>
<div class="son">
<!-- 4、在子组件中使用 -->
<h4>{
{
message }}</h4>
<h4>父组件传递的变量:{
{
num }}</h4>
</div>
</template>
<script setup lang="ts">
// 3、defineProps接收值
// 3.1通过数组的方式接收值
// defineProps(['num','message'])
// 3.2或通过对象的方式接收值
defineProps({
message:String,
num:Number
})
</script>
<style scoped>
.son{
width: 300px;
height: 300px;
background: rgb(227, 210, 219);
}
</style>
效果图:
2、基础的父子通信—子传父
子组件通过自定义事件传值,父组件通过@自定义事件接收
子组件:
<template>
<div class="son">
<!-- 4、子组件中使用 -->
<h4>{
{
message }}</h4>
<h4>父组件传递的变量:{
{
num }}</h4>
<button @click="handler">num+10</button>
</div>
</template>
<script setup lang="ts">
// props的值是只读的,修改父组件传的值,通过自定义事件给父组件传值,通知父组件修改
// 3、defineProps接收值
// 3.1通过数组的方式接收值
// defineProps(['num','message'])
// 3.2通过变量的方式接收值
defineProps({
message:String,
num:Number
})
// a、子组件通过defineEmits传值
const emits = defineEmits(['addNum'])
const handler= ()=>{
emits('addNum',10)
}
</script>
<style scoped>
.son{
width: 300px;
height: 300px;
background: rgb(227, 210, 219);
}
</style>
父组件:
<template>
<div class="box">
<!-- 2、使用组件,并传值【message传的是字符串,num传递的是变量】 -->
<Child message="父组件传给子组件的一段文本值" :num="num" @addNum="handler"></Child>
</div>
</template>
<script setup lang="ts">
// 1、引入子组件
import Child from './Child.vue'
import {
ref} from 'vue'
const num = ref(100)
// b、父组件接收值
const handler = (e:any)=>{
num.value += e
}
</script>
<style scoped>
.box {
display: flex;
justify