组件传值"/>
Vue3中组件传值
推荐:【vue3 <script setup> props 使用与讲解】defineProps、withDefaults 类型限制、默认值设置_普通网友的博客-CSDN博客本章主要涉及api内容:defineProps、withDefaults;defineProps 只能是要么使用`运行时声明`,要么使用`类型声明`。同时使用两种声明方式会导致编译报错。;defineProps、withDefaults 是只在 例子1 > 运行时声明 的方式只能设置参数类型、默认值、是否必传、自定义验证。报错为控制台warn警告。若想设置[ 编辑器报错、编辑器语法提示 ]则需要使用类型声明的方式。<script lang='ts' setup>c..
父子组件传值 【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中应用
组件封装示例:://blog.csdn/qq_40323256/article/details/130832252
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; // 未设置默认值,为 undefinedmsg?: 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; // 未设置默认值,为 undefinedmsg?: 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: '',};},
});
更多推荐
Vue3中组件传值
发布评论