vue + element-ui 國際化實現

1. 安裝組件和插件vue

cnpm i element-ui -S // 安裝element
cnpm i vue-i18n -S //安裝i18nnpm

2.將國際化資源放在assets目錄下element-ui

 

3.在src下新建i18n目錄,建立一個 index.js;路徑src\i18n\index.jsapp

import Vue from 'vue'
import VueI18n from 'vue-i18n'

import ElementLocale from 'element-ui/lib/locale'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'

import langZh from "@/assets/languages/zh.js"
import langEN from "@/assets/languages/en.js"

Vue.use(VueI18n)
 
const i18n = new VueI18n({
  locale: 'zh',
  messages: {
    'zh': {...langZh,...zhLocale},
    'en': {...langEN,...enLocale}
  }
})
ElementLocale.i18n((key, value) => i18n.t(key, value))

export default i18n

4.在main.js引用ui

import i18n from './i18n/index'
import locale from 'element-ui/lib/locale/lang/en'

Vue.use(ElementUI, { locale })


new Vue({
  el: '#app',
  i18n,
  router,
  components: { App },
  template: '<App/>'
})

5.頁面中使用$t引用this

  <el-radio v-model="theme" label="1">{{$t('common.risk')}}</el-radio>

6.切換語言spa

            switchLang(val){
                this.$i18n.locale=val; //此處val爲 zh 或者 en
            }
相關文章
相關標籤/搜索