manu1895/laravel-vue-translation-v2

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

v3.0 2022-10-05 16:01 UTC

This package is not auto-updated.

Last update: 2024-09-19 23:55:40 UTC


README

GitHub issues GitHub stars Total Downloads GitHub license

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')

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')
});

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