I18n function-oriented encapsulation uses flow

The directory structure

Prepare translation files (localize locale information)

Prepare both Chinese and English text for locale/lang.js: (of course you can also place both Chinese and English separately in zh.js/en.js)

const locale = {
	'zh-CN': {
		web: {
			title: 'title'.content: 'content'.view: 'View line {index}'.// Support variables}},en: {
		web: {
			title: 'title'.content: 'content'.view'view {index} line',}}}export default locale;
Copy the code

Create an i18N instance

Locale /index.js create i18 instance:

import Vue from 'vue';
import VueI18n from 'vue-i18n';
import messages from './lang';

Vue.use(VueI18n);

export function createI18n(lang = 'zh-CN') {
    return new VueI18n({
    	// Configure the locale
        locale: lang,
        // Configure the default locale
        fallbackLocale: 'zh-CN'.// Compare text (localize locale information)
        messages,
        // Whether to cancel the warning output when localization fails (true: prohibit localization failure warning)
        silentTranslationWarn: true}); }export default createI18n;
Copy the code
  1. For details about i18N parameters, see API reference
  2. Using the idea of functional programming, we wrap a factory function and return a configured instance of i18N. This has the advantage of ensuring that the component is independent. Call directly only when needed, and get the return value, nothing else.

Mount to vUE

Get the current locale by cookie

/ / main. In ts
import Cookies from 'js-cookie';
let lang = Cookies.get('lang') | |'zh-CN';
Copy the code
  1. In this case, the current locale is retrieved by the cookie in the corresponding;
  2. A wave of amwayjs-cookiePlug-in, can easily obtain the value of the cookie, save their own slowly cut;

Import file main.ts

/ / main. In ts
import Vue from 'vue';
import App from './app.vue';
import createI18n from '@/locale';

const i18n = createI18n(lang); // This lang is the locale retrieved from cookie above

newVue({ ... Not to mention vUe-related family buckets, i18n,render: h= > h(App),
    });
Copy the code

Using the $t

<template>
	<div>
	    <head>{{ $t('web.title') }}</head>
	    <div>{{ $t('web.content') }}</div>
            <! The second argument to $t is an object that can pass variables -->
            <div>{{ $t('web.view', {index: 1}) }}</div>
	</div>
</template>
Copy the code

Of course, i18n is much more than these features and Settings, but also a very powerful plug-in, see the documentation for details

Well today share here ~!