vue3的typescript项目-全局组件如何添加类型提示

1,640 阅读1分钟

在使用ts开发的时候,类型提示可以帮我们解决很多问题,提高代码质量。那么开发的自定义全局组件是如何显示提示呢?

1: 建立components.d.ts文件

image.png

2:引入全局组件

image.png

import pageTable from './components/page-table/index.vue';
import pageLayout from './components/page-layout/index.vue';

declare module '@vue/runtime-core' {
  export interface GlobalComponents {
    pageTable: typeof pageTable;
    pageLayout: typeof pageLayout;
  }
}

这时候可以看到类型提示了

image.png

3:组件导出defineComponent函数

image.png

<template>
  <div>sdfsdfs{{ parmas }}</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import type { PropType } from 'vue';

interface typeAttributes {
  url: string;
  methods: string;
  colums: any[];
}

export default defineComponent({
  name: 'pageTable',
  props: {
    parmas: {
      type: Object,
      default() {
        return {};
      },
    },
    attributes: {
      type: Object as PropType<typeAttributes>,
      default() {
        return {
          url: '',
          methods: '',
          colums: [],
        };
      },
    },
  },
});
</script>

最终属性类型提示显示了

image.png

项目地址: https://github.com/WangZhenHao/vite-vue3-admin

qq讨论群: 475870039