1.defineProps 用来接收父组件传来的 props,示例:
子组件:
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { difineProps } from 'vue'
difineProps({
message:{
type:String,
default:'我是默认值'
}
})
</script>
父组件:
<template>
<div>
<childProps :message="message"></childProps>
</div>
</template>
<script setup>
import childProps from './ChildProps '
import { ref } from 'vue'
const message = ref('我是父组件')
</script>
2.defineEmits 子组件向父组件事件传递,示例:
子组件:
<template>
<div>
<<button @click="emitEvent">触发事件</button>
</div>
</template>
<script setup>
import { difineEmits } from 'vue'
const { emit } = difineEmits (['childEvent'])
const emitEvent = ()=>{
const eventData = 'Data to be passed';
emit('childEvent', eventData); // 触发自定义事件,并传递数据
}
</script>
父组件:
<template>
<div>
<child :childEvent="childEvent"></child>
</div>
</template>
<script setup>
import child from './Child '
const childEvent= (data) =>{
console.log(data) //输出子组件的值
}
</script>
3.defineExpose 组件暴露出自己的属性,在父组件中可以拿到值,示例:
子组件:
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { defineProps, defineExpose } from 'vue';
const props = defineProps({
message: {
type: String,
required: true
}
});
const exposedMethods = {
getMessage() {
return props.message;
}
};
defineExpose(exposedMethods);
</script>
父组件:
<template>
<div>
<h3 @click="isclick">我是父组件</h3>
<child ref="child"></child>
</div>
</template>
<script setup>
import child from './child'
import { ref } from 'vue'
const child= ref()
const isclick= () => {
console.log('接收子组件暴漏出来的方法',child.value.exposedMethods.getMessage)
}
</script>
2826




被折叠的 条评论
为什么被折叠?



