How can I use lang class laravel in vue.js 2?

2019-03-03 10:25发布

问题:

My vue component like this :

<template>
    <ul class="nav nav-tabs nav-tabs-bg">
        <li role="presentation" v-for="item in tabs">
            1. failed -> {{ item.name }} 2.success -> {{trans('purchase.payment.tab')}}
        </li>
    </ul>
</template>
<script>
    export default {
        data() {
            return {
                tabs: [
                    {name: "trans('purchase.payment.tab')"}
                ]
            }
        }
    }
</script>

My lang in laravel(resources/lang/en/purchase.php) like this :

<?php
return [
    'payment' => [
        'tab' => 'Payment Status',
    ],
    ...
];

If the component vue executed, the result like this :

  1. failed -> trans('purchase.payment.tab') 2.success -> Payment Status

So, if trans used in data, it does not work

How can I solve this problem?

回答1:

Is not possible to use a PHP helper inside JavaScript. But, you can create an object of translations.

In your AppServiceProvider (you can create a new one if you want):

// Don't forget to import the facade
use Illuminate\Support\Facades\Lang;


public function boot() {
    $translations = [
     'auth' => Lang::get('auth'),
     'pagination' => Lang::get('pagination'),
     'passwords' => Lang::get('passwords'),
     'validation' => Lang::get('validation'),
   ];

   view()->share('translations', json_encode($translations));

}

In your HTML (I suggest header) you can just call:

window.app = {
    translations: {!! $translations !!},
}

And to access using in JS, you can just do this, for example:

this.app.translations.auth.throttle // Too many login attempts. Please try again in :seconds seconds.


回答2:

I use vue-i18n for that. That way you should make its own dictionary. I made a i18n/en.js file;

module.exports = {
    login: {
      title: 'Login',
      loginButton: 'Login',
      emailInput: 'email',
      passwordInput: 'password',
    },
    Form: {
      title: 'Form',
    }
}

and a i18n/hu.js with the same variables in Hungarian. Then I made a i18n/map.js file:

var en = require('./en.js');
var hu = require('./hu.js');

module.exports = {
  en,
  hu,
}

and finally, set it in vue.js, check my app.js file part:

require('./bootstrap'); // vue comes from here
import VueI18n from 'vue-i18n'
import dictionary from './i18n/map'

var localeTmp = document.documentElement.lang;
var locale = "hu";
if(localeTmp) {
  locale = localeTmp
}

const i18n = new VueI18n({
  locale: locale, // set locale
  dictionary, // set map of dictionary
})
....
const app = new Vue({
    el: 'app',
    i18n,
});

Its a very elegant way.

and how I use in component? simple:

  ....
  <md-input-container>
    <md-icon>person</md-icon>
    <label>{{ $t("loginForm.emailInput") }}</label>
    <md-input email name="email" required v-model="email" />
  </md-input-container>
  ....