1、注册全局组件
在
src/component/global
中新建index.ts
文件,用了导入全局组件并注册
index.ts
内容:
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
注册全局 【推荐】
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中引入注册全局组件
main.ts
内容:
import { createApp } from 'vue';
import App from './App.vue';
import useGlobalComponents from './components/global';
const app = createApp(App);
useGlobalComponents(app);
app.mount('#app');
若采用install
方式注册全局,则用app.use
方式来注册
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进行类型提示
在
main.ts
同级目录中,新建components.d.ts
文件,用来处理组件引入报错问题及添加组件提示
components.d.ts
内容:
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、直接使用全局组件
经过上述三个步骤,就可以在其他
.vue
中直接使用我们注册的全局组件了,并不需要每个单独引入,且会有相关组件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>