vue2.0 多語言切換


vue i18n 是Vue的國際化插件,使用它我們可以輕松的在我們的項目中進行多語言的切換。

1.1 安裝

npm install vue-i18n

2.2 配置main.js


// i18n
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'zh',
  messages: {
    'zh': require('./i18n/lang/zh'),
    'en': require('./i18n/lang/en')
  }
})

new Vue({
  router,
  i18n
}).$mount('#app')

3.3 新建語言文件

  • src文件夾下面新建lang文件夾,zh.js(中文)、en.js(英文)。

zh.js:


module.exports = {
  home: '主頁',
  date: '日期'
}

en.js:


module.exports = {
  home: 'home',
  date: 'date'
}
  

4.4 使用


<template>
  <div>
    <div class="locale-changer">
      <select v-model="$i18n.locale">
        <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">
          {{ lang }}
        </option>
      </select>
    </div>
    <div>{{ $t('home')}}</div>
    <div>{{ $t('date')}}</div>
  </div>
</template>

<script>
  export default {
    name: 'App',
    data() {
      return {
        langs: ['zh', 'en']
      }
    }
  }
</script>

5.5 保存用戶習慣

在上面的例子中我可以發現當我們刷新了以后,前次設置的語言類型並沒有保存。需要我們在每次進去頁面都手動選擇,所以我們使用localstorage保存默認的語言類型。

修改main.js:


const i18n = new VueI18n({
  locale: localStorage.getItem('locale') || 'zh',
  messages: {
    'zh': require('./i18n/lang/zh'),
    'en': require('./i18n/lang/en')
  }
})

App.vue:


<template>
  <div>
    <div class="locale-changer">
      <select v-model="$i18n.locale" @change="selectI18($event)">
        <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">
          {{ lang }}
        </option>
      </select>
    </div>
    <div>{{ $t('home')}}</div>

    <div>{{ $t('date')}}</div>
  </div>
</template>

<script>

...

methods: {
      selectI18(e){
          localStorage.setItem('locale', e.target.value);
      }

<script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM