在项目入口文件 main.ts 里注册组件
// main.ts
import { createSSRApp } from 'vue'
import MeleonUI from '@/ml-ui/lib'
import MlButton from '@/ml-ui/lib/ml-button/index.vue'
import App from './App.vue'
export function createApp() {
const app = createSSRApp(App)
app.use(MeleonUI)
app.component('MlButtonGlobal', MlButton)
return {
app
}
}
使用插件方法,在组件文件夹内部定义组件注册方法
// meleon-ui.ts
import type { App, Plugin } from 'vue'
import MlButton from './ml-button'
const components: Record<string, Plugin> = {
MlButton,
}
const install = (app: App) => {
for (const key in components) {
if (Object.prototype.hasOwnProperty.call(components, key)) {
app.use(components[key])
}
}
}
const MeleonUI = { install }
export default MeleonUI
// ml-button/index.ts
import type { App } from 'vue'
import _Button from './index.vue'
const install = async (app: App) => {
app.component('MlButton', _Button)
}
export default { install }
最后编译到微信小程序中,入口文件注册的组件会被编译成函数形式,而组件文件夹内部注册的组件则被编译成了对象,实际使用也是前者可以被正确渲染出来,为什么会有这种区分呢?