父子组件传值 【defineEmits、defineProps】
Child.vue
<template>
<p>用户名:{{ username }}</p>
<button @click="fn">点击</button>
</template>
<script setup>
const props = defineProps({
username: { type: String, default: "张三" },
});
const emit = defineEmits(["fn"]);
const fn = () => {
emit("fn", 2);
};
</script>
App.vue
<template>
<h1>hello vue3</h1>
<Child :username="msg" @fn="test"></Child>
</template>
<script setup>
import Child from "@/components/Child.vue";
let msg = ref("李四");
const test = (value) => {
console.log("value:", value);
};
</script>
兄弟组件传值 mitt
安装mitt
npm i -S mitt
新建utils/bus.js文件
import mitt from 'mitt'
const emiiter = mitt()
export default emiiter
A组件中发布事件:
<template>
<p>这是A页面</p>
<button @click="btn">点击</button>
</template>
<script setup>
import emitter from "@/utils/bus";
const str = ref("我是A组件的数据");
const btn = () => {
emitter.emit("fn", str);
};
</script>
B组件中监听事件,并在组件销毁时取消监听:
<template>
<p>这是B页面</p>
{{ s }}
</template>
<script setup>
import emitter from "@/utils/bus";
const s = ref(""); // 等待接收
const handelEventFn = (e) => {
s.value = e.value;
};
onBeforeMount(() => {
emitter.on("fn", handelEventFn); // 开启监听,监听到fn事件后,执行handelEventFn函数
});
onUnmounted(() => {
emitter.off("fn"); // 取消fn事件的全部处理函数的监听
});
</script>
爷传值给子,孙【provide、inject】
在孙中改变爷传递过来的值,则其他子孙的值都会改变
TypeScript中应用
defineProps
const props2 = defineProps<{
either: "必传且限定" | "其中一个" | "值";
child?: string | number;
strData?: string;
arrFor: any[];
}>();
withDefaults 定义默认值
interface的方式
调用时直接:props.msg
interface Props {
either: "必传且限定" | "其中一个" | "值";
child: string | number;
strData: string;
sda?: string; // 未设置默认值,为 undefined
msg?: string;
labels?: string[];
obj?: { a: number };
}
const props = withDefaults(defineProps<Props>(), {
msg: "hello",
labels: () => ["one", "two"],
obj: () => {
return { a: 2 };
},
});
type的方式:
type TProps = {
either: "必传且限定" | "其中一个" | "值";
child: string | number;
strData: string;
sda?: string; // 未设置默认值,为 undefined
msg?: string;
labels?: string[];
obj?: { a: number };
};
const props = withDefaults(defineProps<TProps>(), {
msg: "hello",
labels: () => ["one", "two"],
obj: () => {
return { a: 2 };
},
});
方式2:
interface IProps {
previewStyle: IPointStyle;
dialogType: TDialogType;
layer_uuid: string;
markStyle: IMarkStyle;
featureList?: IFeatureItem[];
}
const props = withDefaults(defineProps<IProps>(), {
previewStyle: () => {
return {
kind: 'Icon',
image: '',
};
},
});