1、props
概述:props是使用频率最高的一种通信方式,常用与:父<——>子。
- 若 父传子:属性值是非函数。
- 若 子传父:属性值是函数。
父组件:
<template>
<div class="father">
<h3>父组件</h3>
<h4>汽车:{
{car}}</h4>
<h4 v-show="toy">子给的玩具:{
{toy}} </h4>
<Child :car="car" :sendToy="getToy" />
<div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import {ref} from 'vue'
//数据
let car = ref('奔驰')
let toy = ref('')
// 方法
function getToy(value:string){
toy.value = value
}
</script>
<template>
<div class="child">
<h3>子组件</h3>
<h4>玩具:{
{toy}}</h4>
<h4>父给的车:{
{car}} </h4>
<button @click="sendToy(toy)">把玩具给父亲</button>
<div>
</template>
<script setup lang="ts" name="Child">
import {ref} from 'vue'
//数据
let toy = ref('奥特曼')
// 声明接收props
defineProps(['car','sendToy'])
</script>
2、自定义事件
<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'
let toy = ref('奥特曼')
//声明事件
const emit = defineEmits(['send-toy'])
</script>
<template>
<div class="father">
<h3>父组件</h3>
<h4 v-show="toy">子给的玩具:{
{toy}}</h4>
<Child @send-toy='saveToy'/>
<div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import {ref} from 'vue';
let toy = ref('')
function saveToy(value:string){
console.log('xyz',value)
toy.value = value
}
</script>
3、mitt
安装mitt
npm i mitt
>> utils/emitter.ts
// 引入mitt
import mitt from 'mitt'
// 调用mitt得到emitter.能绑定事件,触发事件
const emitter = mitt()
// 绑定时间
emitter.on('test1',()=>{
console.log('test1被调用了')
})
emitter.on('test2',()=>{
console.log('test2被调用了')
})
// 触发事件
setImterval(() => {
emitter.emit('test1')
emitter.emit('test2')
},2000);
setTimeout(()=>{
//emitter.off('test1')
//emitter.off('test2')
emitter.all.clear()
},3000);
//暴露
export fefault emitter
>> main.ts
import emitter from '@/utils/emitter'
>> Child1.vue
<template>
<div class="child1">
<h3>子组件1</h3>
<h4>玩具:{
{toy}}</h4>
<button @click="emitter.emit('send-toy',toy)">玩具给弟弟</button>
</div>
</template>
<script setup lang="ts" name="Child1">
import {ref} from 'vue'
let toy = ref('奥特曼')
</script>
>> Child2.vue
<template>
<div class="child2">
<h3>子组件2</h3>
<h4>电脑:{
{computer}}</h4>
<h4>哥哥给的玩具:{
{toy}}</h4>
</div>
</template>
<script setup lang="ts" name="Child2">
import {ref,onUnmounted} from 'vue'
import emitter from '@/utils/emitter';
let computer= ref('联想')
let toy = ref('')
// 给emitter绑定send-toy事件
emitter.on('send-toy',(value:string)=>{
toy.value = value
})
//在组件卸载时解绑send-toy事件
onUnmounted(()=>{
emitter.off('send-toy')
})
</script>