欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 父组件调用子组件的方法

父组件调用子组件的方法

2025/2/24 0:54:42 来源:https://blog.csdn.net/bluejad/article/details/144401269  浏览:    关键词:父组件调用子组件的方法

父组件

在父组件中调用子组件的sayHello()函数

<template><div><button @click="getChild('wendu')">触发子组件方法wendu</button><button @click="getChild('shidu')">触发子组件方法shidu</button><el-dialog v-model="dialogVisible" title="title" width="80%" draggable style="background: #091b37 !important; padding:1px !important" :close-on-click-modal="false"><transition><keep-alive><component :is="Child" ref="childRef" :key="b"> </component></keep-alive></transition></el-dialog></div>
</template>
<script setup>
import { ref, nextTick } from 'vue'
import Child from './components/wendu.vue'const b = ref('')
const dialogVisible = ref(false)
// 定义与 ref 同名变量
const childRef = ref(null)
const getChild = (a) => {dialogVisible.value = trueb.value = anextTick(() => {if (childRef.value) {console.log(childRef.value);console.log(childRef.value.sayHello);childRef.value.sayHello(a);} else {console.log("子组件尚未渲染");}})
}
</script>

子组件

<template><div>我是子组件</div><input type="text" v-model="inputValue">
</template><script setup>
import { ref, defineExpose } from 'vue'// 第一步:定义子组件的方法
const sayHello = (value) => {console.log(value)
}
// 第二部:暴露方法
defineExpose({sayHello 
})
</script>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词