• Vue.use原理及源码解读


    vue.use(plugin, arguments) 语法

      》参数:plugin(Function | Object)

      》用法:

        如果vue安装的组件类型必须为Function或者是Object;

        如果是个对象,必须提供install方法;

        如果是一个函数,会被直接当作install函数执行;

        install函数接受参数,默认第一个参数为Vue,其后参数为注册组件时传入的arguments;

    组件.js
        export const testObj = {
            install(Vue, arg) {
                
            }
        }
        export const testFn = founction(Vue, arg) {
            
        }
        
    index.js
        import { testObj, testFn } from './组建.js'
        Vue.use(testObj, arg)
        Vue.use(testFn, arg)
        

      建议组件采用第一种写法,根据use源码,当采用第二种写法时,this指针指向null

      

    if (typeof plugin.install === 'function') {
        plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
        plugin.apply(null, args)
    }

      官方Vue.user()源码分析

    // Vue源码文件路径:src/core/global-api/use.js
    import { toArray } from '../util/index'
    
    export function initUse (Vue: GlobalAPI) {
     Vue.use = function (plugin: Function | Object) {
    // 限制了自定义组建的类型
       const installedPlugins = (this._installedPlugins || (this._installedPlugins =
    []))
    //保存注册组件的数组,不存在及创建
       if (installedPlugins.indexOf(plugin) > -1) {
    //判断该组件是否注册过,存在return Vue对象
         return this
       }
    //调用`toArray`方法
       const args = toArray(arguments, 1)
       args.unshift(this)
    //将Vue对象拼接到数组头部
       if (typeof plugin.install === 'function') {
    //如果组件是对象,且提供install方法,调用install方法将参数数组传入,改变`this`指针为该组件
         plugin.install.apply(plugin, args)
       } else if (typeof plugin === 'function') {
    //如果传入组件是函数,这直接调用,但是此时的`this`指针只想为`null` 
         plugin.apply(null, args)
       }
    //在保存注册组件的数组中添加
       installedPlugins.push(plugin)
       return this
     }
    }

      toArray方法源码

    export function toArray (list: any, start?: number): Array<any> {
      start = start || 0
      let i = list.length - start
    //将存放参数的数组转为数组,并除去第一个参数(该组件)
      const ret: Array<any> = new Array(i)
    //循环拿出数组
      while (i--) {
        ret[i] = list[i + start]
      }
      return ret
    }

    原博地址:https://www.jianshu.com/p/710fbbff15ba

    相关博客:https://www.jianshu.com/p/89a05706917a

         https://segmentfault.com/a/1190000012296163

  • 相关阅读:
    linux下安装rpc.rstatd
    myeclipse下编译jmeter2.4
    2010我最喜爱的耳机评选结果q
    HTTP/1.1 Range和ContentRange
    top命令的load average是什么意思?
    用户 'sa' 登录失败。该用户与可信 SQL Server 连接无关联。
    自定义ListBox,实现单多选切换(复选框)
    自定义水印输入框和密码框
    获取Windows Phone设备信息
    启动器和选择器学习(7)选择器之联系人信息保存
  • 原文地址:https://www.cnblogs.com/aidixie/p/15596655.html
Copyright © 2020-2023  润新知