Vue3组件通信
Vue3组件通信和Vue2的区别:
1、移出事件总线,使用mitt代替
2、vuex换成了pinia
3、把.sync优化到了v-model里面了
4、把$listeners所有的东西,合并到$attrs中了
5、$children被砍掉了
props
若 父传子:属性值是非函数。若 子传父:属性值是函数
父传递给子,是以属性的方式传递,子组件通过defineProps去接收
子传递给父,父组件需要创建一个函数去接取,并通过属性传给子组件,子组件通过defineProps去调用那个方法
//父组件
<template><div class="father"><h3>父组件,</h3><h4>我的车:{{ car }}</h4><h4>儿子给的玩具:{{ toy }}</h4><Child :car="car" :getToy="getToy"/></div>
</template>
<script setup lang="ts" name="Father">import Child from './Child.vue'import { ref } from "vue";// 数据const car = ref('奔驰')const toy = ref()// 方法function getToy(value:string){toy.value = value}
</script>//子组件
<template><div class="child"><h3>子组件</h3><h4>我的玩具:{{ toy }}</h4><h4>父给我的车:{{ car }}</h4><button @click="getToy(toy)">玩具给父亲</button></div>
</template>
<script setup lang="ts" name="Child">import { ref } from "vue";const toy = ref('奥特曼')defineProps(['car','getToy'])
</script>自定义事件
自定义事件常用于:子 => 父
注意区分好:原生事件、自定义事件
原生事件:
- 事件名是特定的(
click、mosueenter等等) - 事件对象
$event: 是包含事件相关信息的对象(pageX、pageY、target、keyCode)
自定义事件
- 事件名是任意名称
- 事件对象
$event: 是调用emit时所提供的数据,可以是任意类型!!!
//父组件
<template><div class="father"><h3>父组件,</h3><h4>我的车:{{ car }}</h4><h4>儿子给的玩具:{{ toy }}</h4><Child @send-toy="saveToy"/></div>
</template>
<script setup lang="ts" name="Father">import Child from './Child.vue'import { ref } from "vue";// 数据const car = ref('奔驰')const toy = ref('')// 方法function saveToy(value:string){toy.value = value}
</script>//子组件
<template><div class="child"><h3>子组件</h3><h4>我的玩具:{{ toy }}</h4><button @click="emit('send-toy',toy)">玩具给父亲</button></div>
</template>
<script setup lang="ts" name="Child">import { ref } from "vue";const toy = ref('奥特曼')const emit = definEmits(['send-toy'])
</script>