首页
视频
资源
登录
小可爱
什么时候才能领悟,取之越多失之越多
博主信息
排名
6
文章
6
粉丝
16
评论
8
文章类别
ASP.NET
16篇
JS
1篇
.NET
23篇
英语
4篇
redis
4篇
随笔
30篇
EF
3篇
前端
53篇
.net core
25篇
python
8篇
版本控制
1篇
java
2篇
nginx
2篇
docker
6篇
后端
5篇
更多
mysql
8篇
数据库
15篇
微服务
4篇
移动开发
7篇
架构
6篇
linux
2篇
最新文章
最新评价
{{item.articleTitle}}
{{item.blogName}}
:
{{item.content}}
关于我们
ICP备案 :
渝ICP备18016597号-1
网站信息:
2018-2024
TNBLOG.NET
技术交流:
群号656732739
联系我们:
contact@tnblog.net
欢迎加群
欢迎加群交流技术
转
vue3父组件调用子组件方法。vue3父子组件方法调用
2009
人阅读
2023/7/22 10:02
总访问:
879863
评论:
0
收藏:
1
手机
分类:
前端
vue3父组件调用子组件的方法是通过expose和ref来实现的,我们可以通过expose来控制父组件可以访问子组件那些的方法和对象,我们将通过setup api(组合式 api)和option api(选项式 api)来演示父组件如何调用子组件的方法。 ###组合式API 父组件通过ref定义子组件实例,通过调用实例获得子组件的数据和方法 ``` <!-- 父组件 app.vue --> <template> <div class="itxst"> <!-- 使用 ref 指令关联子组件 --> <child ref="childComp"/> <button @click="onTry">点击试一试</button> </div> </template> <script setup> import { reactive, ref } from "vue"; import child from "./child.vue"; //定义子组件实例,名称要和上面的ref相同 const childComp = ref(null); //访问demo组件的方法或对象 const onTry = () => { //获取到子组件的 title 数据 let msg = childComp.value.state.title; //调用子组件的 play方法 childComp.value.play(); }; </script> ``` 子组件通过defineExpose暴露对象和方法 ``` <!--子组件名称 child.vue --> <template> <div class="itxst"> {{ state.title }} </div> </template> <script setup> import { ref, reactive } from "vue"; //定义一个变量 const state = reactive({ title: "www.itxst.com", }); //定义一个方法 const play = () => { state.title = "你调用了子组件的方法"; }; //暴露state和play方法 defineExpose({ state, play, }); </script> ``` ### 选项式API 父组件: ``` <!-- 父组件 app.vue --> <template> <div class="itxst"> <!-- 使用 ref 命令 --> <child ref="childComp"/> <button @click="onClick">点击试一试</button> </div> </template> <script > import child from "./child.vue"; export default { name: "app", //注册组件 components: { child, }, methods: { onClick: function () { //获取到 子组件的 数据 let msg = this.$refs.childComp.message; //执行了子组件的 play方法 this.$refs.childComp.play(); }, }, }; </script> ``` 子组件: ``` <!-- 子组件 child.vue --> <template> <div class="itxst"> {{ title }} </div> </template> <script> //选项式默认当前实例是全部暴露 export default { name: "demo", //默认全部暴露 也可以通过expose控制那些需要暴露 //expose: ['play'], data() { return { title: "www.itxst.com", }; }, methods: { play: function () { this.title = "你调用了子组件的方法"; }, }, }; </script> ``` 原文:https://blog.csdn.net/weixin_42252416/article/details/128001894
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
👈{{preArticle.title}}
👉{{nextArticle.title}}
评价
{{titleitem}}
{{titleitem}}
{{item.content}}
{{titleitem}}
{{titleitem}}
{{item.content}}