tohidplus / laravel-vue-translation
一个提供 Laravel 翻译功能的 VueJs 包
3.0.0
2023-04-23 11:35 UTC
Requires
- elementaryframework/fire-fs: 1.2.2
README
Laravel 在 VueJS 中的翻译
此包可以帮助您在客户端应用程序中(尤其是在 Vue js 中)实现 Laravel 翻译功能
开始使用
通过 Composer 安装此包
composer require tohidplus/laravel-vue-translation
在 config/app.php 文件中添加服务提供者
'providers' => [ // Tohidplus\Translation\TranslationServiceProvider::class, // ];
运行命令以发布包资源
php artisan vendor:publish --provider="Tohidplus\Translation\TranslationServiceProvider"
这将发布 Translation.js 文件到 resources/js/VueTranslation 目录
运行 artisan 命令
php artisan VueTranslation:generate --watch=1
这将编译 resources/lang 目录中的所有翻译文件,生成 resources/js/VueTranslation/translations.json 文件
打开 resources/js/app.js 文件并添加 Translation 辅助函数
window.Vue = require('vue'); // If you want to add to window object window.translate=require('./VueTranslation/Translation').default.translate; // If you want to use it in your vue components Vue.prototype.translate=require('./VueTranslation/Translation').default.translate;
运行命令以编译资源
npm run development // or watch or production
如何切换语言?
这将从文档的 lang 属性获取当前语言
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> </body> </html>
如何使用?
假设这是 resources/lang 目录的结构
|--en |--auth.php |--pagination.php |--passwords.php |--validation.php |--messages.php |--fr |--auth.php |--pagination.php |--passwords.php |--validation.php |--messages.php
而 messages.php 文件可能如下所示
return [ 'foo'=>[ 'bar'=>'Some message' ] ];
您可以通过调用 translate 方法来获取值
translate('messages.foo.bar') // or apply the sentence based translation withint splitting on dots(.) translate('Some full translation. Like this one.', {}, false)
Vue 组件中的示例
<template> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">Example Component</div> <div class="card-body"> {{translate('messages.foo.bar')}} </div> </div> </div> </div> </div> </template> <script> export default { } </script>
使用备用语言环境
要像 Laravel 中的 trans() 一样交互,请将以下代码插入布局中
<meta name="fallback_locale" content="{{ config('app.fallback_locale') }}">
替换属性
不建议使用此包来显示验证错误,但如果需要,可以通过传递对象作为第二个参数来替换 :attribute、:size 等。
translate('validation.required',{ attribute:translate('validation.attributes.title') });
注意:如果无法找到传递的键的值,则将返回确切的键