如何在 Laravel 项目中本地化 SFC Vue.js 组件

How to localize SFC Vue.js Component in Laravel Project

当我在 SFC vue 组件中本地化时

{{ $t('foo') }}

然后我在控制台收到这个错误,我怎么调用$t函数

Property or method "$t" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

先添加本地化需要的包

yarn add vue-i18n @kazupon/vue-i18n-loader

然后将以下配置添加到webpack.mix.js,确保i18n()应该在js()

之前
mix.extend( 'i18n', new class {
    webpackRules() {
        return [
            {
                resourceQuery: /blockType=i18n/,
                type:          'javascript/auto',
                loader:        '@kazupon/vue-i18n-loader',
            },
        ];
    }
}(),
);

mix.i18n()
    .js('resources/js/app.js', 'public/js')

添加resources/js/utils/i18n.js,我们将从locale目录

读取配置
import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

function loadLocaleMessages () {
  const locales = require.context('../locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
  const messages = {}
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)
    if (matched && matched.length > 1) {
      const locale = matched[1]
      messages[locale] = locales(key)
    }
  })
  return messages
}

export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})

创建目录locales并创建文件resources/js/locales/en.json,只需添加以下内容

{
    "foo": "bar",
}

现在让我们在 resources/js/app.js

中导入 i18n 包
import router from '@/router'
import i18n from '@/utils/i18n'

const el = "#app"
const app = new Vue({ i18n, router, el });

终于可以在Vue组件文件中使用本地化字符串了

{{ $t('foo') }}

你可以在vue文件中定义i18n规则

<template>
  <button>{{ $t('Save') }}
</template>
<i18n>
{
  "en": {
    "Save": "Save Now"
  }
}
</i18n>