vue3 全局组件 及 ts 提示

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>

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值