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>

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐