我正在开发Vue应用的laravel。在laravel中,我使用View::share(' key ',' value ');所以我在所有刀片文件中获取所有键值。但是在vue组件中,我不会为所有Vue组件获取这个密钥。
发布于 2020-02-05 11:52:20
最后,我解决了这个问题。
首先创建一个翻译服务提供者:
<?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文件中注册它:
'providers' => [
// your other providers
App\Providers\TranslationServiceProvider::class,
],然后,
必须在刀片模板中将翻译字符串传递给JS。我是在默认布局/app.blde.php文件中这样做的:
<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
}
},
}和最后一步是将该方法作为一个混合体包括在内:
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>https://stackoverflow.com/questions/60044735
复制相似问题