父组件调用子组件
同vue2
一、父 → 子:props
父组件传数据给子组件:
<!-- 父组件 -->
<ChildComponent :message="hello" :count="5" />
<!-- 子组件 -->
<script setup>
const props = defineProps({
message: String,
count: Number
})
</script>
二、子 → 父:emit
子组件触发事件,父组件监听:
<!-- 子组件 -->
<script setup>
const emit = defineEmits(['update', 'close'])
function handleClick() {
emit('update', { value: 123 })
}
</script>
<!-- 父组件 -->
<ChildComponent @update="handleUpdate" />
<script setup>
function handleUpdate(data) {
console.log(data.value) // 123
}
</script>
三、父访问子:expose + ref
父组件直接调用子组件的方法或访问数据:
<!-- 子组件 -->
<script setup>
import { ref } from 'vue'
const count = ref(0)
function reset() {
count.value = 0
}
defineExpose({ count, reset }) // 必须 expose 才能被父访问
</script>
<!-- 父组件 -->
<ChildComponent ref="childRef" />
<script setup>
import { ref } from 'vue'
const childRef = ref(null)
function callChild() {
childRef.value.reset() // 调用子组件方法
}
</script>
升级写法:v-model(双向绑定语法糖)
本质是 props + emit 的封装,适合表单类组件:
<!-- 父组件 -->
<ChildComponent v-model="value" />
<!-- 等价于 -->
<ChildComponent :modelValue="value" @update:modelValue="value = $event" />
<!-- 子组件 -->
<script setup>
defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
function onChange(val) {
emit('update:modelValue', val)
}
</script>