辅助理解 Props + Emits
官网原文地址:
Props互动教程
https://cn.vuejs.org/tutorial/#step-12
Emits互动教程
https://cn.vuejs.org/tutorial/#step-13
如下代码的大致流程
TypeScript
子组件点击按钮
↓
emit('increment', i)
↓
父组件 @increment 接收
↓
handleIncrement(val)
↓
父组件执行逻辑
App.vue
TypeScript
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const greeting = ref('Hello from parent')
const handleIncrement = (val) => {
console.log('子组件传回来的值:', val)
}
</script>
<template>
<!-- 父组件可以使用 v-on 简写@ 监听子组件触发的事件 -->
<ChildComp :msg="greeting" @increment="handleIncrement"/>
</template>
ChildComp.vue
TypeScript
<script setup>
// 声明触发的事件
const emit = defineEmits(['increment'])
// defineProps() 是一个编译时宏,并不需要导入
const props = defineProps({
msg: String
})
let i = 0
const increment123 = () => {
// 带参数触发
emit('increment', i++)
}
</script>
<template>
<h2>{{ msg || 'No props passed yet' }}</h2>
<button @click="increment123">子组件点我</button>
</template>
💡 关键理解(非常重要)
❌ 错误思维
子组件去"改父组件逻辑"
✅ 正确思维
子组件只负责"发信号"
最终你要形成的"脑内模型"
TypeScript
数据在父组件(ref)
↓
props 传给子组件
↓
子组件不能改 props
↓
只能 emit 通知父组件改
↓
父组件更新 → props 再下发
++仅供学习参考++