create account

多国语言组件vue-i18n / 网络研习社#75 by lemooljiang

View this thread on: hive.blogpeakd.comecency.com
· @lemooljiang ·
$3.11
多国语言组件vue-i18n / 网络研习社#75
![language.jpg](https://steemjiang.com:8081/ipfs/QmPPSHAkjjZuzuJVNpL3sQ4dnHrCRL8FXcH5F5tfQcnHde)

vue-i18n是个非常实用的多国语言组件!当你的网站要配置多种语言的界面时,用它是首选。用起来倒也容易,翻下手册,看几个实用的案例,就基本上八九不离十啰。可以说,上手的成本挺小的。

[参考手册](https://kazupon.github.io/vue-i18n/zh/)

```js
npm install vue-i18n --save

//main.js
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)
const DEFAULT_LANG = navigator.language
// console.log(888, 'DEFAULT_LANG', DEFAULT_LANG)  //888 "DEFAULT_LANG" "zh-CN"  "DEFAULT_LANG" "en"
const LOCALE_KEY = 'localeLanguage'
const i18n = new VueI18n({
  locale:'zh-CN',
  messages: {
    'zh-CN': require('./assets/lang/zh_CN'),
    'en': require('./assets/lang/EN')
  },
  fallbackLocale: 'zh-CN'
})
const setup = lang => {
  if (lang === undefined){
    lang = window.localStorage.getItem(LOCALE_KEY)
    if (i18n.messages[lang] === undefined){
      lang = DEFAULT_LANG
    }
  }
  window.localStorage.setItem(LOCALE_KEY, lang)
  Object.keys(i18n.messages).forEach(lang => {
    document.body.classList.remove(`lang-${lang}`)
  })
  document.body.classList.add(`lang-${lang}`)
  document.body.setAttribute('lang', lang)

  Vue.config.lang = lang
  i18n.locale = lang
}
setup()

//切换
setzhlang(){
  let LOCALE_KEY = 'localeLanguage'
  let lang = 'zh-CN'
  localStorage.setItem(LOCALE_KEY, lang)
  this.$i18n.locale = 'zh-CN'
},
setenlang(){
  let LOCALE_KEY = 'localeLanguage'
  let lang = 'en'
  localStorage.setItem(LOCALE_KEY, lang)
  this.$i18n.locale = 'en'
}

//html
{{ $t('message.orderNumber') }}
 {{ $t('message.paymentMethod') }}
```

在`./assets/lang/zh_CN`这个文件夹下配置中文或是其它的语言包就要可以,然后配上前端的语言切换就可以了。还是相当易用的。
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorlemooljiang
permlinkvue-i18n-75
categoryhive-105017
json_metadata{"tags":["cn","network-institute","vue","vue-i18n","language"],"image":["https://steemjiang.com:8081/ipfs/QmPPSHAkjjZuzuJVNpL3sQ4dnHrCRL8FXcH5F5tfQcnHde"],"links":["https://kazupon.github.io/vue-i18n/zh/"],"app":"hiveblog/0.1","format":"markdown"}
created2020-12-22 14:16:00
last_update2020-12-22 14:16:00
depth0
children0
last_payout2020-12-29 14:16:00
cashout_time1969-12-31 23:59:59
total_payout_value1.610 HBD
curator_payout_value1.502 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,601
author_reputation442,111,264,000,381
root_title"多国语言组件vue-i18n / 网络研习社#75"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id101,049,024
net_rshares17,426,654,788,960
author_curate_reward""
vote details (38)