1、注冊(cè)全局組件
在
src/component/global
中新建index.ts
文件店溢,用了導(dǎo)入全局組件并注冊(cè)
index.ts
內(nèi)容:
import type { Component, App } from 'vue';
import MButton from './MButton.vue';
import MInput from './MInput.vue';
import MCheckbox from './MCheckbox.vue';
const components: {
[propName: string]: Component;
} = {
MButton,
MInput,
MCheckbox
};
const useGlobalComponents = (app: App) => {
for (const key in components) {
app.component(key, components[key]);
}
};
export default useGlobalComponents;
或采用install
注冊(cè)全局 【推薦】
import type { Component, App } from 'vue';
import MButton from './MButton.vue';
import MInput from './MInput.vue';
import MCheckbox from './MCheckbox.vue';
const components: {
[propName: string]: Component;
} = {
MButton,
MInput,
MCheckbox
};
export default {
install: (app: App) => {
for (const key in components) {
app.component(key, components[key]);
}
}
};
2弟跑、在main.ts中引入注冊(cè)全局組件
main.ts
內(nèi)容:
import { createApp } from 'vue';
import App from './App.vue';
import useGlobalComponents from './components/global';
const app = createApp(App);
useGlobalComponents(app);
app.mount('#app');
若采用install
方式注冊(cè)全局娜汁,則用app.use
方式來注冊(cè)
import { createApp } from 'vue';
import App from './App.vue';
import globalComponents from './components/global';
const app = createApp(App);
app.use(globalComponents)
app.mount('#app');
3都弹、編寫.d.ts進(jìn)行類型提示
在
main.ts
同級(jí)目錄中仁锯,新建components.d.ts
文件仙蚜,用來處理組件引入報(bào)錯(cuò)問題及添加組件提示
components.d.ts
內(nèi)容:
import MButton from '@/components/global/MButton.vue';
import MInput from '@/components/global/MInput.vue';
import MCheckbox from '@/components/global/MCheckbox.vue';
declare module '@vue/runtime-core' {
export interface GlobalComponents {
MButton: typeof MButton;
MCheckbox: typeof MCheckbox;
MInput: typeof MInput;
}
}
4此洲、直接使用全局組件
經(jīng)過上述三個(gè)步驟,就可以在其他
.vue
中直接使用我們注冊(cè)的全局組件了委粉,并不需要每個(gè)單獨(dú)引入黍翎,且會(huì)有相關(guān)組件TS提示。
<script lang='ts' setup>
import { ref } from 'vue';
const numValue = ref(0)
</script>
<template>
<m-input v-model="numValue" placeholder="please input" type="number" />
</template>