packages\runtime-core\src\apiCreateApp.ts文件内有下面代码

use(plugin, ...options) {
  if (plugin && isFunction(plugin.install)) { // 一般插件都是触发第一个条件
    installedPlugins.add(plugin)
    plugin.install(app, ...options)
  } else if (isFunction(plugin)) {
    installedPlugins.add(plugin)
    plugin(app, ...options)
  }
  return app
},

vue-router插件,就是这样写的

export function createRouter(options) {
  const router = {
    options, 
    current: ref(window.location.hash.slice(1) || '/'),
    install(app) {
      app.component('RouterLink', RouterLink)
      app.component('RouterView', RouterView)
      app.config.globalProperties.$router = this
    }
  } 
  window.addEventListener('hashchange', () => {
    router.current.value = window.location.hash.slice(1)
  })
  return router
}

我们在main.js内去use触发源码中的use函数

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
createApp(App).use(router).mount("#app");
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐