营销型网站seo,公司网站域名如何申请,新乡市四合一网站建设,内蒙古做网站的公司有哪些【Vue3】组件通信之自定义事件 背景简介开发环境开发步骤及源码总结 背景
随着年龄的增长#xff0c;很多曾经烂熟于心的技术原理已被岁月摩擦得愈发模糊起来#xff0c;技术出身的人总是很难放下一些执念#xff0c;遂将这些知识整理成文#xff0c;以纪念曾经努力学习奋… 【Vue3】组件通信之自定义事件 背景简介开发环境开发步骤及源码总结 背景
随着年龄的增长很多曾经烂熟于心的技术原理已被岁月摩擦得愈发模糊起来技术出身的人总是很难放下一些执念遂将这些知识整理成文以纪念曾经努力学习奋斗的日子。本文内容并非完全原创大多是参考其他文章资料整理所得感谢每位技术人的开源精神。
简介
本文介绍 Vue3 中如何通过自定义事件实现子组件向父组件传数据。
Vue3 中组件间通信包括
父组件向子组件传数据实现方案有 propsv-model$refs默认插槽 / 具名插槽 子组件向父组件传数据 propsv-model$parent自定义事件作用域插槽 父组件向子组件的子组件传数据即向孙子组件传数据 $attrsprovider inject 任意组件间传数据 mittPinia
开发环境
分类名称版本操作系统WindowsWindows 11IDEVisual Studio Code1.91.1
开发步骤及源码
1 在 【Vue3】组件通信之props 基础上修改 Vue 根组件 src/App.vue在子组件标签上添加一个自定义事件 sync-read-times。
templatediv classparenth1父组件/h1h2Blog数量{{ blogs.length }}/h2h2浏览数量{{ readTimes }}/h2!-- 给子组件绑定了一个 sync-read-times 事件只要 sync-read-times 被触发其指向的 syncReadTimes 函数就会被调用 --Blog :blogsblogs :authorauthor sync-read-timessyncReadTimes //div
/templatescript setup langts
import Blog from ./components/Blog.vue
import { reactive, ref } from vueconst author ref(Nick)const blogs reactive([{ id: 001, title: 美国大选, content: 美国大选将于... },{ id: 002, title: 奥运奖牌, content: 截止今日奥运奖牌榜... },{ id: 003, title: 俄乌战争, content: 乌克兰单方面提出希望和谈... },{ id: 004, title: 巴以冲突, content: 巴以冲突最新战况... },
])const readTimes ref(0)function syncReadTimes(value) {readTimes.value value
}
/scriptstyle scoped langscss
.parent {background-color: orange;padding: 20px;
}
/style2 修改子组件使用 defineEmits 函数声明接收的父组件自定义事件 sync-read-times然后修改 button 点击事件为触发自定义事件 sync-read-times。
templatediv classcontenth1子组件/h1div classblog v-forblog in blogs :keyblog.iddiv classblog-title标题{{ blog.title }}/divdiv classblog-author作者{{ author }}/divdiv classblog-content{{ blog.content }}/divbutton clickemits(sync-read-times, 1)浏览量1/button/div/div
/templatescript setup langts
const data defineProps([author, blogs])
// 声明事件
const emits defineEmits([sync-read-times])
/scriptstyle scoped langscss
.content {background-color: aquamarine;padding: 20px;.blog {border: 1px solid gray;border-radius: 5px;padding: 0 10px;margin-top: 5px;div {padding: 10px 5px;}.blog-title {font-weight: bold;}.blog-author {font-size: small;font-style: italic;}.blog-content {font-size: small;}button {margin: 10px 0;}}
}
/style3 执行命令 npm run dev 启动应用浏览器访问http://localhost:5173/。点击子组件中按钮父组件中的 浏览数量 随按钮点击次数增加。
总结
使用自定义事件实现子组件向父组件传数据
父组件需要在子组件标签上自定义事件格式事件名函数名如本例中的 sync-read-timessyncReadTimes当子组件触发自定义事件 sync-read-times 时父组件的函数 syncReadTimes 就会被调用子组件使用 defineEmits 声明接收的父组件自定义事件defineEmits 函数参数为自定义事件名称数组子组件根据实际需求触发自定义事件触发自定义事件函数本例中的 emits(sync-read-times, 1)的第一个参数为自定义事件名后面跟随自定义事件对应的父组件中函数的参数参数数量不定即向父组件传的数据。