<template><zhapi:name="content"<!-- 传给子组件的值 --><!-- -->:fun="funzi"<!-- 可以把函数传给子组件使用 -->ref="showInfoRef"<!-- 父组件给子组件色值别名showInfoRef -->@handLer="hand"<!-- handLer子组件自定义的事件,hand是父组件的function,子传父内容 -->><templatev-slot:sl<!-- 插槽插入 -->#sl<!-- 插槽插入简写 -->><div>插槽item内容<img src="#" /></div></template></zhapi><button @click="funzi"></button></template><script setup>import {ref,provide} from 'vue';const showInfoRef = ref()const content = ref('张张')//把name提供出去,下面所有层级组件接收注入,如子组件、孙子组件,都接收依赖注入。provide("name", name);function funzi(){showInfoRef.value.zi()//父组件调用子组件的方法}function hand(e){console.log(e)//e是子组件传过来的数据}<script>
<template><div>父组件传过来的值:{{props.name}}</div><button @click="expose">子组件暴露给父组件使用</button><button @click="zifu">子传父</button><slot name="sl"></slot>//插槽</template><script setup>import {ref,inject} from 'vue';const name = inject("name");//接收依赖注入const props = defineProps({//子组件接收父组件传的值name: {type: String,//数据类型,数据类型传错了,会报错提示。default: "张张",//默认值required: true,//当前属性必传,不传也能运行,会报错提示。},age: {type: Number,default: 0},arr:{type:Array,default:[]},fun:{type:Function},})const ArrayList = reactive([{id: 1,name: "法外",},{id: 2,name: "狂徒",}]);function zi(){console.log('父组件直接使用子方法')}const emits = defineEmits(["handLer"]);//使用defineEmits语法糖的方法来创建自定义事件。function zifu(){//子组件传值给父组件emits("handLer", ArrayList);//左边是你的自定义事件名,右边是你要传的数据。};function expose(){console.log(props.name)}// 把expose函数或者ArrayList值暴露出去给父组件使用,所有父组件要使用的数据,必须在这里暴露出去。defineExpose({expose,ArrayList})<script>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号