首页 > 其他分享 >Vue——eventsMixin【十六】

Vue——eventsMixin【十六】

时间:2023-04-24 13:57:51浏览次数:32  
标签:Vue const eventsMixin 十六 vm events cbs event fn

前言

按着流程接下来就到了eventsMixin,这里面其实主要是$on$once$off$emit的方法定义。

内容

eventsMixin位于src/core/instance/events.ts

export function eventsMixin(Vue: typeof Component) {
    const hookRE = /^hook:/
    // https://v2.cn.vuejs.org/v2/api/#vm-on
    Vue.prototype.$on = function (
        event: string | Array<string>,
        fn: Function
    ): Component {
        const vm: Component = this
        // 是数组的话就递归调用$on
        if (isArray(event)) {
            for (let i = 0, l = event.length; i < l; i++) {
                vm.$on(event[i], fn)
            }
        } else {
            ; (vm._events[event] || (vm._events[event] = [])).push(fn)
            // optimize hook:event cost by using a boolean flag marked at registration
            // instead of a hash lookup
            if (hookRE.test(event)) {
                vm._hasHookEvent = true
            }
        }
        return vm
    }

    // https://v2.cn.vuejs.org/v2/api/#vm-once
    Vue.prototype.$once = function (event: string, fn: Function): Component {
        const vm: Component = this
        function on() {
            // 监听器触发后就移除
            vm.$off(event, on)
            fn.apply(vm, arguments)
        }
        on.fn = fn
        vm.$on(event, on)
        return vm
    }

    // https://v2.cn.vuejs.org/v2/api/#vm-off
    Vue.prototype.$off = function (
        event?: string | Array<string>,
        fn?: Function
    ): Component {
        const vm: Component = this
        // 没有提供参数,则移除所有的事件监听器
        if (!arguments.length) {
            vm._events = Object.create(null)
            return vm
        }
        // 提供了事件与回调,则只移除这个回调的监听器
        if (isArray(event)) {
            for (let i = 0, l = event.length; i < l; i++) {
                vm.$off(event[i], fn)
            }
            return vm
        }
        // specific event
        const cbs = vm._events[event!]
        // 提供了没有监听的event
        if (!cbs) {
            return vm
        }
        // 只提供了事件,则移除该事件所有的监听器
        if (!fn) {
            vm._events[event!] = null
            return vm
        }
        // specific handler
        // 同时提供了事件与回调,则只移除这个回调的监听器
        let cb
        let i = cbs.length
        while (i--) {
            cb = cbs[i]
            if (cb === fn || cb.fn === fn) {
                cbs.splice(i, 1)
                break
            }
        }
        return vm
    }
    // https://v2.cn.vuejs.org/v2/api/#vm-emit
    Vue.prototype.$emit = function (event: string): Component {
        const vm: Component = this
        if (__DEV__) {
            const lowerCaseEvent = event.toLowerCase()
            if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
                tip(
                    `Event "${lowerCaseEvent}" is emitted in component ` +
                    `${formatComponentName(
                        vm
                    )} but the handler is registered for "${event}". ` +
                    `Note that HTML attributes are case-insensitive and you cannot use ` +
                    `v-on to listen to camelCase events when using in-DOM templates. ` +
                    `You should probably use "${hyphenate(
                        event
                    )}" instead of "${event}".`
                )
            }
        }
        // 从_events中取出对应的event并赋给cbs
        let cbs = vm._events[event]
        if (cbs) {
            cbs = cbs.length > 1 ? toArray(cbs) : cbs
            const args = toArray(arguments, 1)
            const info = `event handler for "${event}"`
            // 遍历cbs数组、调用并传参
            for (let i = 0, l = cbs.length; i < l; i++) {
                // 使用try-catch包裹运行的代码出错时会直接抛给handleError进行处理
                invokeWithErrorHandling(cbs[i], vm, args, vm, info)
            }
        }
        return vm
    }
}

总结

1. $on 方法定义
2. $once 方法定义
3. $off 方法定义
4. $emit 方法定义

标签:Vue,const,eventsMixin,十六,vm,events,cbs,event,fn
From: https://www.cnblogs.com/wangyang0210/p/17349221.html

相关文章

  • vue移动端使用(pdfh5) 组件预览PDF
    1、安装插件npmipdfh52、在页面内引入组件importPdfh5from"pdfh5";import"pdfh5/css/pdfh5.css";3、写一个展示pdf文件的容器  <divid="pdfType"></div>4、封装在事件中 initPdf(){      this.pdfh5=''      this.pdfh......
  • 在vue标签代码块中定义变量
     方式一:<template><h1>test</h1><template:set="first=list[0]">//定义变量<div>{{first.name}}</div>//使用变量</template>...</template><script>exportdefault{......
  • 3.Vue脚手架
    3.脚手架3.1.初识3.1.1.简介Vue脚手架/Cli(CommandLineInterface)是Vue官方提供的标准化开发工具(开发平台)。官网:https://cli.vuejs.org/zh/3.1.2.安装全局安装@vue/cli(第一次使用时配置即可)npminstall-g@vue/cli#在使用这串命令之前需要下载好nodejs并且......
  • 【vue】error in ./src/components/NumberInfo/NumberInfo.vue
    出现背景:ant designvuepro执行yarnrunserve解决办法:修改src/components/NumberInfo.vue文件中style部分原来的:<stylelang="less"scoped>@import"index";</style>注释掉 @import"index"<stylelang="less"scoped&g......
  • Vue学习笔记之Node Sass version 8.0.0 is incompatible with 4.0.0错误
    输入以下两个命令:npmuninstallnode-sassnpmi-Dsass注:Mac环境如果进行了系统升级,需要重新安装Xcode,执行命令xcode-selectinstall不然会出现如下的错误Mac解决gyp:NoXcodeorCLTversiondetected!报错 如果出现python2的错误gypverb`which`failedE......
  • 记录在vue3项目中使用wangeditor富文本编译器以及微信小程序中的渲染
    首先,管理后台中的使用npminstallwangeditor//f封装成了组件,以下是组件中的内容<template>  <divstyle="border:1pxsolid#ccc;maxwidth:600px">   <!--工具栏-->   <Toolbar    style="border-bottom:1pxsolid#ccc"    :......
  • ai问答:使使用 Vue3 组合式API 和 TypeScript 父子组件demo
    这是一个使用Vue3组合式API和TypeScript的简单父子组件示例父组件Parent.vue:<template><div><p>{{msg}}</p><Child/></div></template><scriptlang="ts">import{ref}from'vue'import......
  • Vue3 Suspense
    视频3.Suspense等待异步组件时渲染一些额外内容,让应用有更好的用户体验使用步骤:异步引入组件import{defineAsyncComponent}from'vue'constChild=defineAsyncComponent(()=>import('./components/Child.vue'))使用Suspense包裹组件,并配置好default与fallba......
  • Vue3 Teleport
    视频2.Teleport什么是Teleport?——Teleport是一种能够将我们的组件html结构移动到指定位置的技术。<teleportto="移动位置"> <divv-if="isShow"class="mask"> <divclass="dialog"> <h3>我是一个弹窗</h3> <button@clic......
  • Vue 创建一个Vue项目
    首先,init一个项目D:\javawebPractce\Vue这是我的工程路径创建命令vueinitwebpackhello-vuehello-vue是我的项目名称创建之后,我为了方便,将router自动安装了安装elementUInpmielement-ui-S安装组件npmstall安装sass加载器cnpminstallsass-loadernode-sass--......