1、Props
props用于父组件向子组件传值。
子组件通过props从父组件索取数据,父组件调用子组件时,将props中定义的参数传入即可。
①子组件 ChildComp.vue
<script setup>
// defineProps() 是一个编译时宏,并不需要导入。一旦声明,msg prop 就可以在子组件的模板中使用。
const props = defineProps({
msg: String
})
</script>
<template>
// msg不为空则直接显示,否则显示后面的
<h2>{{ msg || 'No props passed yet' }}</h2>
</template>
②父组件中调用子组件,并传参
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const greeting = ref('Hello from parent')
</script>
<template>
// :msg将msg绑定到greeting
<ChildComp :msg="greeting" />
// 将msg的值直接传给子组件
<ChildComp msg="greeting" />
</template>
③返回结果为
2、Emits
emits用于子组件向父组件传值。
由于VUE的机制原因,子组件不能直接向父组件传值,需要通过触发事件向父组件传值。
①子组件 ChildComp.vue
<script setup>
// defineEmits用来声明emit事件,名为response
const emit = defineEmits(['response'])
// 使用emit()将response事件和数据,传递给父组件
emit('response', 'hello from child')
</script>
<template>
<h2>Child component</h2>
</template>
②父组件调用子组件,并响应事件
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const childMsg = ref('No child msg yet')
</script>
<template>
// 绑定事件@response,将从子组件接收的数据赋值给childMsg
<ChildComp @response="(msg) => childMsg = msg" />
// 子组件显示完成后,显示childMsg的内容
<p>{{ childMsg }}</p>
</template>
③返回结果为
3、Slots
Slots用于父组件向子组件传递模板片段
①子组件 ChildComp.vue
<template>
<slot>Fallback content</slot>
</template>
②父组件
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const msg = ref('from parent')
</script>
<template>
// 将Message: {{ msg }}传给子组件
<ChildComp>Message: {{ msg }}</ChildComp>
</template>
③返回结果为