父组件向子组件传值: 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接受一个数组,元素为自定义事件名 defineEmits返回一个触发器,用于触发事件,第一个参数是具体事件,第二个是传递的值
//父组件
<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>
其实用的最多的,还是v-model双向绑定的问题,解决办法就是defineProps配合defineEmits使用,实现父子相互赋值:
v-model cannot be used on a prop, because local prop bindings are not writable.
Use a v-bind binding combined with a v-on listener that emits update:x event instead.
相关代码如下:
