Vue.use()源码解读

本文介绍了Vue.use()方法的基本使用,需在new Vue()前调用,插件只会安装一次。阐述了其原理,包括判断插件类型、是否已注册等。还扩充了call和apply的知识及apply的巧用,最后说明可通过Vue.use()全局扩展组件和第三方插件,提高项目扩展性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本使用方法
官方文档传送门
使用Vue.use()方法注册插件的时候,可以传入函数或带有install方法的对象,如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。

Vue.use()方法需要在调用 new Vue() 之前被调用。

当 install 方法被同一个插件多次调用,插件将只会被安装一次。

Vue.use()方法需要在new Vue()之前调用
原理
源码如下:

/* @flow */

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 this
    }

    // additional parameters
    const args = toArray(arguments, 1)
    args.unshift(this)
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin)
    return this
  }
}
  • 判断plugin是否是方法或对象

  • 判断是否已注册过这个插件,每个组件保证只能注册一次

  • 取Vue.use()参数

    其中用到的toArray方法如下:

/**
 - Convert an Array-like object to a real Array.
 */
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.use()方法传入的参数,除第一个参数外(第一个参数是plugin),其他参数存储在args数组中用于apply方法

  • 判断插件是否有install方法,如果有则执行install方法,否则直接把plugin当做install执行
if (typeof plugin.install === 'function') {
   plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
   plugin.apply(null, args)
}

如果插件有install方法,通过apply方法绑定this到plugin对象
如果插件本身没有install方法,apply方法中的this指向null,执行plugin方法

  • 通过installedPlugins注册plugin插件

扩充知识
1.call和apply的作用和区别

作用:通常用于改变this指向
区别:接收函数的方式不同
call(context,x1,x2,…) 不支持数组形式参数
apply(context,[x1,x2,…]) 支持数组形式参数

2.apply()巧用

求数组最大值:Math.max()入参不支持数组,可以通过Math.max.apply(null,array)的方式实现
合并数组:Array.prototype.push.apply(arr1,arr2)

一般在目标函数只需要n个参数列表,而不接收一个数组的形式([param1[,param2[,…[,paramN]]]]),可以通过apply的方式巧妙地解决这个问题

3.Vue.use()全局扩展组件、第三方插件等

项目中新建plugins.js,添加以下内容

import axios from './axiosPath'
import Vant from 'vant'
import TestComponent from './TestComponent'
export default function(Vue) {
   //注册第三方插件
   Vue.use(Vant)
   //全局挂载
   Vue.prototype.$axios = axios
   //全局注册组件
   Vue.component('TestComponent', TestComponent)
}

main.js中注册plugin

import plugins from './plugins.js'
Vue.use(plugins)

这样配置,修改全局组件或全局挂载参数,进修改plugin.js文件即可,扩展性比较好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值