• Vue.use的实现原理


    一、Vue.use 是做什么的?

    • use 概念
      如果你希望编写一个 Vue.js 插件来扩展应用的功能,需要提供一个 install 方法。如果插件是一个对象,那么这个对象必须包含 install 方法;如果插件是一个函数,那么这个函数将被作为 install 方法。当 install 方法被调用时,Vue 实例会作为参数传入,这样插件就不再需要直接依赖 Vue。(扩展应用的功能)

    示例:

    // 定义一个插件对象
    const MyPlugin = {
      // 定义 install 方法
      install(Vue) {
        // 添加全局方法或属性
        Vue.myGlobalMethod = function() {
          // 全局方法逻辑
        };
    
        // 添加全局指令
        Vue.directive('my-directive', {
          bind(el, binding, vnode, oldVnode) {
            // 全局指令逻辑
          }
        });
    
        // 添加实例方法
        Vue.prototype.$myMethod = function(methodOptions) {
          // 实例方法逻辑
        };
      }
    };
    
    // 使用插件
    Vue.use(MyPlugin);
    
    • 插件的功能
      添加全局指令、全局过滤器(Vue3 不再支持过滤器)、全局组件。
      通过全局混入来添加一些组件选项。
      添加实例方法,通过把它们添加到 Vue.prototype / app.config.globalProperties上实现。
    • 实现原理
    Vue.use = function (plugin) {
      // 插件缓存
      const installedPlugins = this._installedPlugins || (this._installedPlugins = []);
      
      // 检查是否已经安装过该插件,如果是则直接返回
      if (installedPlugins.indexOf(plugin) > -1) {
        return this;
      }
    
      // 整合除了第一个参数(plugin)之外的其他参数为数组
      const args = toArray(arguments, 1);
    
      // 将 Vue 实例作为第一个参数放入数组中
      args.unshift(this);
    
      // 判断插件类型并安装
      if (typeof plugin.install === "function") {
        // 如果插件是一个对象,则调用其 install 方法
        plugin.install.apply(plugin, args);
      } else if (typeof plugin === "function") {
        // 如果插件是一个函数,则直接调用该函数
        plugin.apply(null, args);
      }
    
      // 将插件缓存起来
      installedPlugins.push(plugin);
    
      // 返回 Vue 实例
      return this;
    };
    

    Vue3 中使用app.use进行插件的注册,原理同 Vue2~

  • 相关阅读:
    0903(046天 线程集合总结01)
    LeetCode581+621+207
    Pr:更改剪辑的速度和持续时间
    Spring-ApplicationContext refresh的流程
    linux学习实操计划0101-linux卸载软件
    .netcore6.0自己配置swagger
    矿物结构和构造的区别
    SpringMVC:绝对地址、相对地址(动力)
    设计模式-工厂方法
    036、目标检测-锚框
  • 原文地址:https://blog.csdn.net/weixin_47818125/article/details/139327049