defineProps
和 defineEmits
都是只能在<script setup>中使用的编译器宏。他们不需要导入,且会随着 <script setup> 的处理过程一同被编译掉。
官网传送门
父组件向子组件传值
defineProps
是 Vue3 中一种新的组件数据传递方式,可以用于在子组件中定义接收哪些父组件的 props。当父组件的 props 发生变化时,子组件也会随之响应。
在子组件中可以使用 defineProps
声明该组件需要接收的 props,示例如下:
父组件
<script setup lang="ts">
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
const count = ref(0)
const add = () => {
count.value++
}
</script>
<template>
<button @click="add">+</button>
<ChildComponent :count="count"></ChildComponent>
</template>
子组件
<script setup lang="ts">
const props = defineProps({
count: Number
})
</script>
<template>
<div>
{{ props.count }}
</div>
</template>
子组件向夫组件传值
defineEmits
用于在setup
中注册自定义事件,是一个宏函数,使用时无需导入
defineEmits
接受一个数组,元素为自定义事件名
defineEmit
返回一个触发器,用于触发事件,第一个参数是具体事件,第二个是传递的值
父组件
<script setup lang="ts">
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
const count = ref(0)
const changeFn = (val: number) => {
console.log(val)
count.value = count.value + val
}
</script>
<template>
<ChildComponent :count="count" @add="changeFn"></ChildComponent>
</template>
子组件
<script setup lang="ts">
const props = defineProps({
count: Number
})
const emit = defineEmits(['add'])
const change = () => {
emit('add', 1)
}
</script>
<template>
<div>
{{ props.count }}
</div>
<button @click="change">+</button>
</template>