父组件传参,子组件接收
const prop = defineProps({
title: {
type: String,
default: 'ssd',
},
});
interface props {
title: number;
}
const prop = withDefaults(defineProps<props>(), { title: 123 });
console.log(prop.title);
子组件传参,父组件接收
const emit = defineEmits(['onClick']);
interface emits {
(e: 'onClick', name: string): void;
}
const emit = defineEmits<emits>();
const handleClick = () => {
emit('onClick', 'menffy');
};
子组件对父组件暴露方法或变量
defineExpose({
exposeValue: '123',
exposeOpen: () => console.log('子组件暴露的方法被调用啦!!!!!'),
showClientSize: () => {
console.log('clientLeft', document.body.clientLeft);
console.log('clientHeight', document.body.clientHeight);
console.log('clientTop', document.body.clientTop);
console.log('clientWidth', document.body.clientWidth);
},
});
完整例子
父组件
<template>
<div>
<test ref="TestRef" :title="12" @on-click="getSub" />
<t-button @click="handleExpose">子组件暴露的方法或变量</t-button>
</div>
</template>
<script lang="ts">
export default {
name: 'ApplyAWSIndex',
};
</script>
<script setup lang="ts">
import { ref } from 'vue';
import Test from './test.vue';
const TestRef = ref<InstanceType<typeof Test>>();
const getSub = (args) => {
console.log(args);
};
const handleExpose = () => {
console.log('暴露的子组件变量:', TestRef.value?.exposeValue);
console.log('暴露的子组件方法:', TestRef.value?.exposeOpen());
console.log('暴露的子组件方法:', TestRef.value?.showClientSize());
};
</script>
<style scoped></style>
子组件
<template>
<div>
<span>{{ title }}</span>
<t-button @click="handleClick">传递给父组件</t-button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
interface props {
title: number;
}
const prop = withDefaults(defineProps<props>(), { title: 123 });
console.log(prop.title);
interface emits {
(e: 'onClick', name: string): void;
}
const emit = defineEmits<emits>();
const handleClick = () => {
emit('onClick', 'menffy');
};
defineExpose({
exposeValue: '123',
exposeOpen: () => console.log('子组件暴露的方法被调用啦!!!!!'),
showClientSize: () => {
console.log('clientLeft', document.body.clientLeft);
console.log('clientHeight', document.body.clientHeight);
console.log('clientTop', document.body.clientTop);
console.log('clientWidth', document.body.clientWidth);
},
});
</script>
<style scoped></style>