**1.props通信**
props可以实现父子组件通信,在vue3中我们可以通过defineProps获取父组件传递的数据。且在组件内部不需要引入defineProps方法可以直接使用!
<template>
<div class="son">
<h1>我是子组件曹操</h1>
<p>{{info}}</p>
{{money}}
</div>
</template>
<script lang="ts" setup>
defineProps(['info','money'])
</script>
<script>
export default{
props:['info','money']
}
</script>
<style scoped>
.son{
width: 400px;
height: 200px;
background: hotpink;
}
</style>
**2.自定义事件**
在vue框架中事件分为两种:一种是原生的DOM事件,另外一种自定义事件。
原生DOM事件可以让用户与网页进行交互,比如click、dbclick、change、mouseenter、mouseleave....
自定义事件可以实现子组件给父组件传递数据
<template>
<div class="child">
<p>我是子组件2</p>
<button @click="handler">点击我触发自定义事件xxx</button>
<button @click="$emit('click','AK47','J20')">点击我触发自定义事件click</button>
</div>
</template>
<script setup lang="ts">
let $emit = defineEmits(['xxx','click']);
const handler = () => {
$emit('xxx','东风导弹','航母');
};
</script>
<style scoped>
.child {
width: 400px;
height: 200px;
background: pink;
}
</style>
<template>
<div>
<h1>事件</h1>
<pre @click="handler">
大江东去浪淘尽,千古分流人物
</pre>
<button @click="handler1(1,2,3,$event)">点击我传递多个参数</button>
<hr>
<Event1 @click="handler2"></Event1>
<hr>
<Event2 @xxx="handler3" @click="handler4"></Event2>
</div>
</template>
<script setup lang="ts">
import Event1 from './Event1.vue';
import Event2 from './Event2.vue';
const handler = (event)=>{
console.log(event);
}
const handler1 = (a,b,c,$event)=>{
console.log(a,b,c,$event)
}
const handler2 = ()=>{
console.log(123);
}
const handler3 = (param1,param2)=>{
console.log(param1,param2);
}
const handler4 = (param1,param2)=>{
console.log(param1,param2);
}
</script>
<style scoped>
</style>