美文网首页
Vue.use源码

Vue.use源码

作者: 明里人 | 来源:发表于2019-09-25 10:42 被阅读0次
官方对 Vue.use() 方法的说明:

通过全局方法 Vue.use() 使用插件;
Vue.use 会自动阻止多次注册相同插件;
它需要在你调用 new Vue() 启动应用之前完成;
Vue.use() 方法至少传入一个参数,该参数类型必须是 Object 或 Function,如果是 Object 那么这个 Object 需要定义一个 install 方法,如果是 Function 那么这个函数就被当做 install 方法。在 Vue.use() 执行时 install 会默认执行,当 install 执行时第一个参数就是 Vue,其他参数是 Vue.use() 执行时传入的其他参数。

源码:
// Vue源码文件路径:src/core/global-api/use.js

import { toArray } from '../util/index'

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {  // use接收的参数限制是函数或对象两种类型
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > -1) {  // 判断插件是否被注册过
      return this
    }

    const args = toArray(arguments, 1) // 将传入的参数(除plugin)外整理成数组
    args.unshift(this) // 将Vue作为数组的第一项
    if (typeof plugin.install === 'function') { // plugin为对象,并且属性install为函数
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') { // plugin为函数
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin) // 标记已注册
    return this
  }
}

// Vue源码文件路径:src/core/shared/util.js

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
}
Vue作用:

在 install 里可以拿到 Vue, 可以在 install 里处理逻辑,如:进行全局注册组件等。
component.js

import a from './a'
import b from './b'
let components = { a, b }
const installBase = {
   install (Vue) {
      Object.keys(components).map(key => Vue.component(key, components[key]))
   }
}

main.js

import Vue from 'vue'
import component from './component.js'
Vue.use(component)

new Vue({
 ...
})

相关文章

  • 【vue学习】Vue.use

    一、源码分析 用vue插件时,我们会引入插件后,调用下Vue.use(),如: 为啥要执行下Vue.use()呢?...

  • 关于Vue.use()

    在vue开发当中,Vue.use()用于引入组件。下面是use.js的源码··· }} ···从源码中可以看到,u...

  • Vue.use源码

    官方对 Vue.use() 方法的说明: 通过全局方法 Vue.use() 使用插件;Vue.use 会自动阻止多...

  • Vue.use为什么可以注册插件

    源码位置 vue\src\core\global-api\use 我们先从Vue.use这个API的使用开始入手:...

  • Vue.use源码解析

    什么是Vue插件 关于什么是Vue插件大家可以去看官网的解释 ,总得来说就是提供一个全局注册/调用的能力。 怎么用...

  • Vue.use 源码分析

    文章首次发表在 个人博客 vue提供了 Vue.use 的全局api来注册插件,了解它的内部实现,无论是看插件的源...

  • Vue源码浅析01

    Vue源码大致可以理解分为:初始化属性、方法(Vue.use、***等等)和实例化(new Vue)执行的一些方法...

  • Vue.use() 注册插件(个人笔记)

    Vue.use是什么? 官方对 Vue.use() 方法的说明:通过全局方法 Vue.use() 使用插件,Vue...

  • vuex源码解读&简易实现

    源码解读 首先,我们从使用方法入手,一步步来看 接下来 从store.js文件入手。Vue.use(Vuex): ...

  • Vue.use, Vue.component,router-vi

    ? Vue.use Vue.use 的作用是安装插件 Vue.use 接收一个参数 如果这个参数是函数的话,Vue...

网友评论

      本文标题:Vue.use源码

      本文链接:https://www.haomeiwen.com/subject/lguiuctx.html