Vue TypeScript 项目中 "this" 的范围

Scope of "this" in Vue TypeScript project

我在 Table.vue 中有以下带有 i18n 的代码:

<template>
  <div :data="artikel">
    <b-table
      ...
      :fields="fields"
      ...
    ></b-table>
  </div>
</template>

@Component({
  name: 'Table',
})
export default class Table extends Vue {
  ...
  public fields:field[] = [
  {
    key: 'pn_document_id',
    label: 'id',
    class: 'text-left',
    sortable:true
  },
  {
    key: 'url',
    label: this.$i18n.t('image').toString(), // <--- works fine
    class: 'text-center'
  },
  ...
}

我想将字段 (public fields:field[]) 放入外部文件。 所以我创建了 fields.ts,内容如下:

import { field } from '@/types/interfaces';

export let fields: field[] = [
  {
    key: 'pn_document_id',
    label: 'id',
    class: 'text-left',
    sortable:true
  },
  {
    key: 'url',
    label: this.$i18n.t('image').toString(), // <--- this does not work, "this" does not related to vue
    class: 'text-center'
  },
...

问题是,我无法告诉 Vue/TypeScript 我在导入文件中有这个 "this"。我该怎么做?

您不能使用 this 在组件定义之外引用 Vue 组件。但是你可以使用 vue-i18n 全局对象

// setup-vue-i18n.js
const i18n = new VueI18n({
  locale: 'ja', // set locale
  messages, // set locale messages
})

export default i18n
// fields.ts
import i18n from `setup-vue-i18n`

export let fields: field[] = [
  {
    key: 'pn_document_id',
    label: 'id',
    class: 'text-left',
    sortable:true
  },
  {
    key: 'url',
    label: i18n.t('image').toString(),
    class: 'text-center'
  }
]