Skip to content
0

Vue 语言服务

Vue 组件相关服务

组件元信息

分析 Vue 组件的一些 meta 信息 vuejs/language-tools/component-meta

vue-component-meta 允许通过静态代码分析从组件中提取元数据,例如 props、slots、events 等。甚至可以从源代码生成 props 的描述。这有助于组件文档化

使用例子

import type { MetaCheckerOptions } from 'vue-component-meta'
import { createComponentMetaChecker } from 'vue-component-meta'

const checkerOptions: MetaCheckerOptions = {
  forceUseTs: true,
  noDeclarations: true,
  schema: { ignore: ['MyIgnoredNestedProps'] },
  printer: { newLine: 1 },
}

const tsconfigChecker = createComponentMetaChecker(
  // Write your tsconfig path
  'path/to/project/tsconfig.json',
  checkerOptions,
)

const meta = tsconfigChecker.getComponentMeta('path/to/project/src/components/xx.vue')

console.log(meta)
/*
{
  type: [Getter],
  props: [Getter],
  events: [Getter],
  slots: [Getter],
  exposed: [Getter]
}
*/

其支持分析多种形式写法的 Vue 组件。从官方提供的测试文件中可以查看全部 case

比如 jd-solanki/anu 就使用了它生成组件文档 API 部分的信息

类型提取

我们可以使用 vuejs/language-tools/component-type-helpers 进行体操类型转换,帮助我们从 Vue 组件 得到 props 等的 TS 信息

使用例子

import HelloWorld from './HelloWorld.vue'
import type { ComponentProps, ComponentSlots } from 'vue-component-type-helpers'

type Props = ComponentProps<typeof HelloWorld> // { msg: string }
type Slots = ComponentSlots<typeof HelloWorld> // { header(_: { num: number; }): any; footer(_: { str: string; }): any; }
<template>
	<slot name="header" :num="123" />
	<slot name="footer" str="abc" />
</template>

<script lang="ts" setup>
defineProps<{
	msg: string
}>()
</script>

组件预览

上面提到组件文档是组件的一种预览形式,其实我认为还有另一种组件文档的形式,可以在 VsCode 中预览 Vue 组件,绝妙优雅又简便

和上面的包的是同一个作者 johnsoncodehk/vite-plugin-vue-component-preview

需要安装一个 VsCode 插件:Vue and Nuxt Preview

使用的例子如下,扩展了 SFC 的标签,添加了自定义的 <preview> 标签用于定义组件输入的信息

<!-- Component part -->
<template>
	<h1>{{ msg }}</h1>
	<button @click="count++">count is: {{ count }}</button>
</template>

<script setup lang="ts">
import { ref } from 'vue'

defineProps<{ msg: string }>()

const count = ref(0)
</script>

<!-- Preview part -->

<preview lang="md">
  # This is preview page of HelloWorld.vue 

  ## Props 

  | Props       | Description    | 
  | ----------- | -------------- | 
  | msg         | Title message  | 

  ## Examples 

  <script setup> 
  const msgs = [ 
    'Hello Peter', 
    'Hello John', 
  ]; 
  </script> 

  <template v-for="msg in msgs"> 
    <slot :msg="msg"></slot> 
  </template> 

  <style>
    body {
      background-color: green;
    }
  </style>
</preview>

Released under the MIT License.