araфay696/laravel-vue-translation

一个在 VueJs 中实现 Laravel 翻译功能的包

1.4 2023-03-28 11:00 UTC

This package is auto-updated.

Last update: 2024-09-28 14:12:37 UTC


README

GitHub license

Laravel 在 VueJS 中的翻译

此包帮助您在客户端应用程序中实现 Laravel 翻译功能,特别是在 Vue js 中

此包与 Laravel 6.*7.*8.*9.*10.* 兼容

开始使用

通过 composer 安装包

composer require arafay696/laravel-vue-translation

config/app.php 文件中添加服务提供者

'providers' => [
   //
   Devplus\Translation\TranslationServiceProvider::class,
   //
 ];

通过运行命令发布包资源

php artisan vendor:publish --provider="Devplus\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 并添加翻译助手

window.Vue = require('vue');
// If you want to add to window object
window.translate=require('./VueTranslation/Translation').default.translate;
// If you want to import or in Vue3
import { translate } from "./VueTranslation/Translation";

// If you want to use it in your vue components
Vue.prototype.translate=require('./VueTranslation/Translation').default.translate;
// If you want to use it in Vue3, Define it globally 
app.config.globalProperties.translate = 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')
});

注意:如果无法找到传递的键的值,它将返回确切的键