Наконец, я решил эту проблему.
Прежде всего создайте поставщика услуг перевода:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;
class TranslationServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
Cache::rememberForever('translations', function () {
return collect([
'php' => $this->phpTranslations(),
'json' => $this->jsonTranslations(),
]);
});
}
private function phpTranslations()
{
$path = resource_path('lang/' . App::getLocale());
return collect(File::allFiles($path))->flatMap(function ($file) {
$key = ($translation = $file->getBasename('.php'));
return [$key => trans($translation)];
});
}
private function jsonTranslations()
{
$path = resource_path('lang/' . app()->getLocale() . '.json');
if (is_string($path) && is_readable($path)) {
return json_decode(file_get_contents($path), true);
}
return [];
}
}
Зарегистрируйте его в config / app . php file:
'providers' => [
// your other providers
App\Providers\TranslationServiceProvider::class,
],
Затем вам нужно передать строки перевода в JS в шаблоне блейда. Я сделал это в файле layouts / app.blade по умолчанию. php file:
<script>
window._translations = {!! cache('translations') !!};
</script>
Теперь вам нужна некоторая функция js для получения переводов и применения замен. Для этого я создал файл trans. js:
module.exports = {
methods: {
/**
* Translate the given key.
*/
__(key, replace) {
let translation, translationNotFound = true
try {
translation = key.split('.').reduce((t, i) => t[i] || null, window._translations.php)
if (translation) {
translationNotFound = false
}
} catch (e) {
translation = key
}
if (translationNotFound) {
translation = window._translations.json[key]
? window._translations.json[key]
: key
}
_.forEach(replace, (value, key) => {
translation = translation.replace(':' + key, value)
})
return translation
}
},
}
И последний шаг - включить метод в качестве mixin:
Vue.mixin(require('./trans'))
Вот и все. Теперь вы можете использовать переводы в Vue компонентах, таких как:
<template>
<div class="card">
<div class="card-header">{{ __('Example Component') }}</div>
<div class="card-body">
{{ __("I'm an example component.") }}
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log(this.__('Component mounted.'))
}
}
</script>