自定义显示 Custom Displays

有关如何在 Directus 中构建自定义显示扩展的指南。显示是小型内联组件,可让您创建在整个应用程序中查看字段值的新方法。

扩展入口点

显示的入口点是扩展包的 src/ 文件夹中的 index 文件。 它导出一个配置对象,其中包含用于配置显示行为的选项。 加载显示时,此对象由 Directus 主机导入。

入口点示例:

js
import DisplayComponent from './display.vue'

export default {
  id: 'custom',
  name: 'Custom',
  icon: 'box',
  description: 'This is my custom display!',
  component: DisplayComponent,
  options: null,
  types: ['string'],
}

可用选项

  • id — 此显示的唯一键。 使用作者前缀来限定专有显示的范围是一种很好的做法。
  • name — 此显示的人类可读名称。
  • icon材料图标集 中的图标名称,或 Directus 自定义图标的扩展列表。
  • description — 应用程序中显示的此显示的简短描述(<80 个字符)。
  • component — 对显示组件的引用。
  • options — 显示器的选项。 可以是选项对象或专用的 Vue 组件。
  • types — 一组支持的类型
  • localTypes — 局部类型数组。 接受 standardfilefilesm2oo2mm2mm2apresentationtranslationsgroup。 默认为“标准”。
  • fields — 如果设置了此选项,显示将获取关系字段。 可以是字段数组或返回字段数组的函数。

显示组件

显示组件是您的扩展的一部分,只要您的显示器应该用于显示字段的值,Directus 应用程序就会呈现该组件。 这个显示组件必须是 Vue 组件。 编写 Vue 组件最直接的方法是使用 Vue 单文件组件语法。

使用 Vue SFC 语法的显示组件示例:

vue
<script>
export default {
  props: {
    value: {
      type: String,
      default: null,
    },
  },
}
</script>

<template>
  <div>Value: {{ value }}</div>
</template>

该字段的当前值通过“value”属性提供给组件。 如果您使用 fields 选项来获取关系字段,则 value 属性将是一个以请求的字段作为键及其各自的值的对象。

可用Props

  • value — 字段的值。
  • interface — 领域的界面。
  • interfaceOptions — 字段界面的选项。
  • type — 字段的类型。
  • collection — 字段的集合名称。
  • field — 领域的关键。

除了这个与 Directus 应用程序通信的简单 API 之外,显示组件是一个空白画布,允许您创建任何您需要的东西。

Vue Version
Directus 应用程序使用 Vue 3。可能有第 3 方库与 Vue 3 不兼容。

功能组件

您可以使用功能组件,而不是在 Vue SFC 文件中定义组件。 这允许您制作不需要呈现完整组件的简单显示:

js
export default {
  id: 'custom',
  name: 'Custom',
  icon: 'box',
  description: 'This is my custom display!',
  component({ value }) {
    return value.toLowerCase()
  },
  options: null,
  types: ['string'],
}

访问内部系统

要访问 API 或商店等内部系统,您可以使用由“@directus/extensions-sdk”包导出的“useApi()”和“useStores()”可组合项。 它们可以像这样在 setup() 函数中使用:

js
import { useApi, useStores } from '@directus/extensions-sdk'

export default {
  setup() {
    const api = useApi()

    const { useCollectionsStore } = useStores()
    const collectionsStore = useCollectionsStore()

    // ...
  },
}

Vue Options API
如果你更喜欢使用 Vue Options API,你可以直接注入 apistores 属性。