vue3:子组件向父组件发送数据(vue@3.2.26)
2023-09-14 09:01:18 时间
一,编写js代码
1,Parent.vue
<template> <div> <Child @eventParent="receiveMessage"></Child> </div> </template> <script> import Child from './Child' export default { name: "Parent", components: { Child, }, setup() { //接收消息 const receiveMessage = (data) => { let msg="code:"+data.code+";msg:"+data.msg; alert(msg); } return { receiveMessage, } } } </script> <style scoped> </style>
2,Child.vue
<template> <div> <button @click="sendToParent">向父组件传递消息</button> </div> </template> <script> export default { name: "Child", setup (props,{emit}) { //向父组件发送消息 const sendToParent = () => { let msg = { code:1, msg:"这是子组件发送的数据", } emit('eventParent',msg) } return { sendToParent, } } } </script> <style scoped> </style>
说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果:
按钮是子组件的元素,点击后能向父组件发送消息,如图:
![](https://img2022.cnblogs.com/blog/1938691/202202/1938691-20220204170501007-796344770.png)
点击后,父组件收到消息后进行响应:
![](https://img2022.cnblogs.com/blog/1938691/202202/1938691-20220204170501008-241854959.png)
三,查看vue的版本:
liuhongdi@lhdpc:/data/vue/demo1$ npm list vue demo1@0.1.0 /data/vue/demo1 ├─┬ @vue/cli-plugin-babel@4.5.15 │ └─┬ @vue/babel-preset-app@4.5.15 │ └── vue@3.2.26 deduped ├─┬ element-plus@1.2.0-beta.6 │ ├─┬ @element-plus/icons-vue@0.2.4 │ │ └── vue@3.2.26 deduped │ ├─┬ @vueuse/core@7.4.1 │ │ ├─┬ @vueuse/shared@7.4.1 │ │ │ └── vue@3.2.26 deduped │ │ ├─┬ vue-demi@0.12.1 │ │ │ └── vue@3.2.26 deduped │ │ └── vue@3.2.26 deduped │ └── vue@3.2.26 deduped └─┬ vue@3.2.26 └─┬ @vue/server-renderer@3.2.26 └── vue@3.2.26 deduped
相关文章
- vue3: 动态修改favicon(网站的ico 图标)(vue@3.2.26)
- vue.js3.x 使用vue3-count-to 组件(到可视区域才start数字滚动 vue@3.2.33 / vue3-count-to@1.1.2)
- vue3: 动态修改favicon(网站的ico 图标)(vue@3.2.26)
- vue3.x:用webpack-bundle-analyzer分析chunk文件过大的原因(vue.js 3.0.5/@vue/cli 4.5.13)
- 【收藏】vue3+vite+ts 封装axios踩坑记录
- vue3面试题:2022 最新前端 Vue 3.0 面试题及答案(持续更新中……)
- 只能用watchEffect才能监听的到vue3 监听父组件传过来的值
- vue3 - 报错 ESLint: Component name "index" should always be multi-word.(vue/multi-word-component-names)
- Vue2.js迁移到Vue3.js的API变化
- vue3 watch 监听 flush post 作用?
- vue3+ts创建二维数组响应式变量及赋值
- Vue3学习笔记(五)——路由,Router
- 7个你需要知道的Vue3技巧
- vue3快速入门-Teleport传送(瞬移组件)