purpose

The project needs to support multiple languages, so we need to extract the static text used in the project and use the language package for management. When switching the language setting, the text display of the whole project can be automatically switched.

The corresponding component VUE-I18N was found in the Vue project, and the code of the project was not changed much, so we used this component to modify the code in the project.

The installation

/ / script into < script SRC = "https://unpkg.com/vue/dist/vue.js" > < / script > < script SRC ="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script> // NPM install vue-i18n/ / yarn Install yarn add vue-i18n Copy the codeCopy the code

Generally used in a project is through the installation package to run, script introduced less.

use

The i18N is configured in the project

import VueI18n from 'vue-i18n' Vue.use(VueI18n) const i18n = new VueI18n({ local: 'cn' messages / / / / set the language pack}) new Vue ({el: '# app,... {cn: {name: 'name'}, us: {name: 'name'}Copy the code

The use of i18n

Simple to use

/ / HTML to use {{}} name packing up {{$t (' name ')}} / / js $t (' name ')Copy the code

Passable variable

Named after the incoming parameters / / / / messages: {cn: {name: 'name: {name}}, us: {name:' the name: {name}}} $t (' name '{name: 'Jack'}) / / Name: Jack/list/incoming parameters / / messages: {cn: {Name: "Name: {0} {1} '}, us: {Name: 'Name: {0}{1}' } } // array $t('name', ['Jack', 'Job']) // object $t('name', {'0':'Jack', '1': 'Job'])Copy the code

v-tCan be used to reference variables, similar to$t

V – t instruction

New Vue({i18n: new VueI18n({locale: 'en', messages: {en: {hello: 'hi {name}! '}, JA: {hello: hello! ' } } }), computed: { nickName () { return 'kazupon' } }, data: { path: 'hello' } }).$mount('#object-syntax') <div id="object-syntax"> <! -- literal --> <p v-t="{ path: 'hello', locale: 'ja', args: { name: 'kazupon' } }"></p> <! -- data biniding via data --> <p v-t="{ path: path, args: { name: NickName}} "> < / p > < / div > < div id =" object - syntax "> < p > こ ん に ち は, kazupon! </p> <p>hi kazupon! </p> </div> copies the codeCopy the code

$t versus v minus t

  • $tIs a method call,v-tIt’s an instruction
  • v-tPerformance than$tEven better, there is a cache of custom instructions
  • $tIt is more flexible and simpler to use

There e are some other uses, please refer to the official documentation for details.