In Vue3, the internationalization plug-in vue-i18n usage records, with VSCode automatic translation plug-in i18n Ally


Documentation: vue-i18n

Release notes:

vue: 3.0.0+

vue-i18n: 9.x version

Install

npm install vue-i18n@9
// 或者
yarn add vue-i18n@9

create instance

  1. srcCreate a new directory under the directory langto store i18nthe configuration.

    New directory names: lang(language), locales(language settings), i18n, these names can vscode-iconsbe detected and beautified by the VSCode icon plug-in ( ).

  2. langUnder the directory, create a new index.jsfile and import it vue-i18n.

  3. Language configuration information is placed in another file.

    For example, setting 英文and 中文two language types: create a new file for storing Chinese configuration zh.jsonand a file for storing English en.json; and then index.jsimport it in.
    insert image description here

vue-i18nUsing createI18ncreate an instance, the following code creates a new i18ninstance:

File location:src/lang/index.js

import {
    
     createI18n } from "vue-i18n";
import EN from "./en";
import ZH from "./zh";

const messages = {
    
    
  zh: {
    
    
    ...ZH,
  },
  en: {
    
    
    ...EN,
  },
};

const i18n = createI18n({
    
    
  locale: "zh", // 设置当前语言类型
  legacy: false, // 如果要支持compositionAPI,此项必须设置为false;
  globalInjection: true, // 全局注册$t方法
  messages,
});

export default i18n;

language profile

// zh.json
{
    
    
  "hello": "你好"
}


// en.json
{
    
    
  "hello": "hello"
}

global registration

i18nBefore the instance is used in the project, it needs to be registered in the entry file.

Enter main.jsthe file, import and register i18n:

import {
    
     createApp } from 'vue'

import App from './App.vue'
import i18n from './lang'

const app = createApp(App)

app.use(i18n)

app.mount('#app')

use

used in the template

Used in templatethe template, this is relatively simple, directly use the global method $t:

<template>
  {
   
   { $t('hello') }}
</template>

Normal display on the page:你好

Switch to English:src/lang/index.js

const i18n = createI18n({
    
    
  locale: "en", // 设置当前语言类型
  legacy: false, // 如果要支持compositionAPI,此项必须设置为false;
  globalInjection: true, // 全局注册$t方法
  messages,
});

Normal display on the page:hello

used in JS

<template>
  {
   
   { $t('hello') }}
</template>
<script>
import {
      
       getCurrentInstance } from "vue";
import i18n from '@/lang'; // 引入i8n实例
import {
      
       useI18n } from 'vue-i18n';
export default {
      
      
  setup() {
      
      
    // 第一种方法:获取i18n实例对象 t 的方法1
    const {
      
       proxy } = getCurrentInstance();
    const t1 = proxy.$t('hello');
    console.log(t1);

    // 第二种方法:获取i18n实例对象 t 的方法1
    const t2 = i18n.global.t('hello');
    console.log(t2);


    // 第三种方法:获取i18n实例对象 t 的方法3
    const {
      
       t } = useI18n() // 解构出t方法
    const t3 = t('hello');
    console.log(t3);
    return {
      
      };
  },
  mounted() {
      
      
    // 第四种方法:获取i18n实例对象 t 的方法4
    const t4 = this.$t('hello');
    console.log(t4);
  },
};
</script>

language switch

Effect

insert image description here

the code

<template>
  <label for="lang-select">Change language:</label>
  <select name="lang" id="lang-select" @change="changeLang">
    <option value="en">English</option>
    <option value="zh" selected>简体中文</option>
  </select>
  <table border="1" cellspacing="0" cellpadding="0">
    <tr>
      <td>模板中使用</td>
      <td> {
   
   { $t('hello') }}</td>
    </tr>
    <tr>
      <td>JS中响应式切换语言</td>
      <td> {
   
   { hel }}</td>
    </tr>
    <tr>
      <td>当前语言类型</td>
      <td> {
   
   { currentLang }}</td>
    </tr>
  </table>
</template>
<script setup>
import {
      
       computed } from 'vue'
import {
      
       useI18n } from 'vue-i18n'
const {
      
       locale, t } = useI18n();
const changeLang = parameter => {
      
      
  const lang = parameter.target.value;
  locale.value = lang; // 切换语言
  localStorage.setItem('LANG', lang); // 本地存储当前语言类型
}
// 获取当前语言类型
const currentLang = computed(() => locale.value);
// JS中响应式切换中英文(写入computed中即可)
const hel = computed(() => t('hello'));
</script>
<style scoped>
table {
      
      
  margin-top: 50px;
}

table tr td {
      
      
  padding: 2px 5px;
}
</style>

VSCode plugin i18n Ally

Documentation: i18n ally

Install i18n Allyplugins in VSCode

insert image description here

enablei18n Ally

The premise is that the plug-in needs to be installed in the project vue-i18n!

Configuration instructions

There are two ways

  1. In the VSCode settings file set
  2. Set in project file (recommended)

In the project file set:

Find .vscodethe folder in the project root directory, addsettings.json

or autogenerated:

In the use record, after completing the steps of creating an instance, you need to restart VSCode,

The following prompt pops up in the lower corner: The translation folder "src/lang" is automatically detected

.vscodeWill automatically create a new file in the project root directorysettings.json

Manual configuration is required:

File location:.vscode/settings.json

Basic Configuration Instructions: Documentation

{
    
    
  "i18n-ally.localesPaths": ["src/lang"], // 翻译文件路径 (自动生成) 相对于项目根目录的语言环境目录路径
  // 如下须要手动配置
  "i18n-ally.keystyle": "nested", // 翻译路径格式 (翻译后变量格式 nested:嵌套式  flat:扁平式)
  "i18n-ally.sortKeys": true,
  "i18n-ally.namespace": true,
  "i18n-ally.enabledParsers": ["json"], // 翻译文件可允许的格式,默认json
  "i18n-ally.sourceLanguage": "zh", // 翻译源语言 (源文件) 根据此语言文件翻译其他语言文件的变量和内容
  "i18n-ally.displayLanguage": "zh", // 显示语言 (显示文件/翻译文件)
  "i18n-ally.translate.engines": ["deepl", "google"], // 翻译器
  "i18n-ally.extract.keygenStyle": "camelCase", // 翻译字段命名样式采用驼峰
  "i18n-ally.enabledFrameworks": ["vue"],
}

After configuration, if it does not take effect, you can try the bottom right corner 修改源语言,

The display language ( i18n-ally.displayLanguage) should not be hard-coded, otherwise the display language will be fixed and 修改显示语言will not take effect

insert image description here


Allowable formats for translation files ( i18n-ally.enabledParsers), fill in JSONor YAMLformats, fully functional. The two language configuration files created earlier zh.jsonand en.json, so fill in here["json"]

Supported locale formats

Format Read Write Annotations Note (note)
JSON
YAML Comments will not be retained
JSON5 Comments will not be retained
THIS Comments will not be retained
properties Comments will not be retained
POT
JavaScript read only
TypeScript read only
PHP read only

The plug-in translator must be connected to a VPN to use

Effect

After the configuration is complete, the display effect is as follows:

EN helloThe subsequent icons are as follows:

  • Open review: comment on copy
  • Translation copy: The translation source language ( "i18n-ally.sourceLanguage": "zh") set in the configuration is Chinese, so there is a translation function for other languages
  • Edit text: quickly edit the text
  • Go to definition: Jump to the original file

insert image description here

Instructions for use

Open a vue file with text content

Open i18n Allythe control panel of

Quickly extract copy (two modes of operation)

The extracted copy will be written to the corresponding translation file of the display language setting:"i18n-ally.displayLanguage": "zh"

  • Expand Hard-coded strings [beta]this item to extract the text individually (you can customize the key value)

insert image description here

  • Right-click Hard-coded strings [beta]this item, select Extract All , and use the default key value.

    Chinese uses pinyin splicing, and the translation field naming style can be changed to hump in the settings:i18n-ally.extract.keygenStyle": "camelCase"

    insert image description here

Extract a single copy

No point of attention.

Extract all copy

It can be seen that the copywriting in the template template has been successfully replaced, but the replacement in the js syntax is still the syntax in vue2.

insert image description here

You can select a single replacement and select the corresponding replacement code. It is also possible to change all matches after extraction this.$t.

insert image description here

zh.jsonhas been successfully written in:

{
    
    
  "hello": "你好",
  "haHaHa": "哈哈哈",
  "dangQianYuYanLeiXing": "当前语言类型",
  "jsZhongXiangYingShiQieHuanYuYan": "JS中响应式切换语言",
  "moBanZhongShiYong": "模板中使用",
  "jianTiZhongWen": "简体中文",
  "english": "English",
  "changeLanguage": "Change language:"
}

Translate missing copy

There is also a function of translating missing copy. After translation, you can directly add the copy to the corresponding file. You need to connect to a VPN to use it, and manual editing is also available.

The translation is based on "i18n-ally.sourceLanguage": "zh"the translation source language set by

insert image description here

Magic VPN - Best Free Proxy Tool

Download the plug-in for the Edge browser, and then download the client to connect to the VPN

Operation example

As follows, after turning on the VPN, click on the missing copy, and zh.jsonthe translated copy will be automatically written into en.jsonthe file according to the JSON field in the file.

If the translation fails after the VPN is turned on, the log will be printed:

ERROR: Error: connect ECONNREFUSED 127.0.0.1:xxxxx

This is because the VPN is turned on after opening the project with VSCode, just restart VSCode.

insert image description here

The translation results are as follows:

{
    
    
  "hello": "hello",
  "changeLanguage": "Change language:",
  "dangQianYuYanLeiXing": "current language type",
  "english": "English",
  "haHaHa": "Hahaha",
  "jianTiZhongWen": "Simplified Chinese",
  "jsZhongXiangYingShiQieHuanYuYan": "Responsive switching language in JS",
  "moBanZhongShiYong": "used in the template"
}

In this way, this plugin saves a lot of work!

Guess you like

Origin blog.csdn.net/qq_51532249/article/details/131442641