vue3中app.use(plugin)的原理
packages\runtime-core\src\apiCreateApp.ts文件内有下面代码vue-router插件,就是这样写的我们在main.js内去use触发源码中的use函数
·
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");
更多推荐
已为社区贡献2条内容
所有评论(0)