# defineProps & defineEmits
// App | |
<template> | |
<div> | |
<h2>App</h2> | |
<h2>当前计数: {{ counter }}</h2> | |
<button @click="increment">+1</button> | |
<Home :message="message" @increment="getCounter"></Home> | |
</div> | |
</template> | |
<script setup> | |
import { ref } from "vue"; | |
import Home from "./Home.vue"; | |
// 计数器 | |
const counter = ref(0); | |
const increment = () => counter.value++; | |
let message = ref("小鸟游六花"); | |
// 接收发射事件 | |
const getCounter = (payload) => { | |
console.log(payload); // 打印传递过来的数据 | |
// 接收传递的数据并再次将 mesage 重新赋值再传回 Home 组件, 在 Home 组件显示。相当于绕了一圈! | |
message.value = payload; | |
}; | |
</script> | |
<style scoped></style> |
// Home | |
<template> | |
<div> | |
<h2>Home</h2> | |
<h2>{{ message }}</h2> | |
<button @click="emitEvent">发射事件</button> | |
</div> | |
</template> | |
<script setup> | |
import { defineProps, defineEmits } from "vue"; | |
const props = defineProps({ | |
message: { | |
type: String, | |
default: "哈哈哈", | |
}, | |
}); | |
let emit = defineEmits(["increment"]); | |
// 发射事件并传递数据 | |
const emitEvent = () => { | |
emit("increment", "樱岛麻衣"); | |
}; | |
</script> | |
<style scoped></style> |
参考结果: