← 返回完整题库
vue.js中等

Vue.use 如何注册插件

参考答案

Vue.use 做了什么

Vue.use = function (plugin) {
  const installed = this._installedPlugins || (this._installedPlugins = [])
  if (installed.indexOf(plugin) > -1) return this        // 幂等去重
  const args = toArray(arguments, 1)
  args.unshift(this)                                     // Vue 构造器放第一位
  if (typeof plugin.install === 'function') plugin.install.apply(plugin, args)
  else if (typeof plugin === 'function') plugin.apply(null, args)
  installed.push(plugin)
  return this                                            // 支持链式
}

要点:

  1. 参数顺序 Vue 在最前,所以 install(Vue, options) 能挂 Vue.prototype.$xxx、Vue.component、Vue.directive、Vue.mixin;
  2. 幂等:_installedPlugins 去重,重复 use 不重复安装;
  3. 返回 this 支持 Vue.use(a).use(b);
  4. Vue 3 对应 app.use(plugin, options),install(app, ...options),通过 app.config.globalProperties、app.component、app.provide 提供能力;内部用 Set 去重。

常见插件内容:全局组件、全局指令、原型方法($http)、全局 mixin、以及 router/pinia 自身。

本题来自 计算机知识面试题库,共 921 道题。