父向子传递
// 父组件
<Child title="我是父组件的标题" :list="[1,2,3]" />
// 子组件接收
import { ref } from "vue";
type Props = {
title: string;
list: number[];
data?: number[]; // ? 可选
};
//const props = defineProps<Props>(); // 第一种
const props1 = withDefaults(defineProps<Props>(), {
// 第二种
data: () => [1, 2, 3, 4], // 当可选未传递时设置默认值, 只有ts语法才有
});
//js中直接使用data报错,必须定义变量props.data使用,模板中可直接使用data
子向父传递
// 子组件
const emit = defineEmits(["change", "click"]); // 定义事件
// 第二种
const emit = defineEmits<{ // ts使用
(e: 'change', name:string, bool: boolean):void
}>();
const change = () => {
emit("change", "testValue", false);
};
// 父组件
<Child @change="handleChange" />
const handleChange = (value, flag) => {
// ...
}
父组件拿到子组件实例
// 父组件拿到子组件实例
<Child ref="instanceRef" /> // ref接受子组件实例
const instanceRef = ref<InstanceType<typeof Child>>(); // 变量名instanceRef 要和组件ref变量一样
const getInstance = () => {
console.log(instanceRef.value);
};
// 子组件向父组件抛出
const list = reactive([]);
defineExpose({
list,
});