1. props:父组件传递数据给子组件
(1)父组件Parent
<!-- 父组件Parent-->
<template>
<div>
<Children :message="parentMessage" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import Children from './Children .vue';
const parentMessage = ref('父组件传递的message');
</script>
(2)子组件Children
<!-- 子组件 Children-->
<template>
<div>
<p>父组件传递: {{ message }}</p>
</div>
</template>
<script setup>
defineProps({
message: {
type: String,
required: true
}
});
</script>
2.emit:子组件传递数据给父组件
(1)子组件Children
<!-- 子组件 Children-->
<template>
<button @click="sendDataToParent">点击我传递数据给父组件</button>
</template>
<script setup>
const emit = defineEmits(['childEvent']);
const sendDataToParent = () => {
emit('childEvent', '来着子组件的数据');
};
</script>
(2)父组件Parent
<!-- 父组件 Parent -->
<template>
<div>
<Children @childEvent="handleChildEvent" />
<p>来着子组件数据: {{ childData }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Children from './Children.vue';
const childData = ref('');
const handleChildEvent = (data) => {
childData.value = data;
};
</script>
3.v-model :双向数据绑定
(1)父组件Parent
<!-- 父组件 Parent -->
<template>
<div>
<Children v-model:message="count" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import Children from './Children.vue';
const count= ref(0)
</script>
(2)子组件Children
<!-- 子组件 Children-->
<template>
<div>{{count}}</div>
<button @click="localCount++">点我+1</button>
</template>
<script setup>
const props = defineProps({
title: String,
count: Number
})
const emit = defineEmits([ 'update:count'])
const localCount = ref(props.count)
watch(localCount, (newVal) => {
emit('update:count', newVal)
})
</script>
4.ref:父组件调用子组件方法
(1)子组件Children
<!-- 子组件 Children -->
<template>
<div>子组件</div>
</template>
<script setup>
const childMethod = () => {
console.log('子组件方法被调用')
}
// 暴露给父组件的方法
defineExpose({
childMethod
})
</script>
(2)父组件Parent
<!-- 父组件 Parent -->
<template>
<Childrent ref="ChildrentRef" />
<button @click="callChildMethod">调用子组件方法</button>
</template>
<script setup>
import { ref } from 'vue'
import ChildrentReffrom './Childrent .vue'
const childRef = ref(null)
const callChildMethod = () => {
ChildrentRef.value.childMethod()
}
</script>