2019-12-16-vue-i18n-前端国际化

vue-i18n-国际化

安装
npm install vue-i18n --save-dev
新建 i18n 文件夹
i18n >
    language >  // 不同的语言翻译
        en-US.js           // 英文
        zh-CN.js           // 中文
    translate.js  //  翻译主体文件
translate.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import enUS from './language/en-US'
import zhCN from './language/zh-CN'
import store from '../store/index'


Vue.use(VueI18n)


let language = window.localStorage.getItem('language'); // 从localStorage获取语言种类
if (!language) { // 如果没有值 把默认值设为中文
    language = 'zh-CN'
    window.localStorage.setItem('language', language) // 把语言种类存到localStorage
}
store.commit('setLanguage', language) // 把语言种类存到vuex
window.console.log(language)
const i18n = new VueI18n({
    locale: store.state.language, // 从vuex中获取语言种类
    messages: {
      'en-US': enUS,
      'zh-CN': zhCN
    },
    silentTranslationWarn: true
})
// window.console.log(i18n.locale)
// window.$i18n = i18n
export { i18n }
en-US.js
const t = {
    main: {
        open: 'open',
        close: 'close',
        sendEmail: 'Send Email'
    }
}
export default t
zh-CN.js
const t = {
    main: {
        open: '打开',
        close: '关闭',
        sendEmail: '发送邮箱'
    }
}
export default t
main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'
import router from './route/index'
import axios from 'axios'
import ViewUI from 'view-design'
import {i18n} from './i18n/translate'
import 'view-design/dist/styles/iview.css';
import '@/assets/css/md.css'
import './assets/css/reset.css'
import 'vant/lib/index.css';
import vant from 'vant';
Vue.use(vant);
// import Echarts from 'echarts'

Vue.use(ViewUI);
Vue.config.productionTip = false
// Vue.use(Echarts)
axios.defaults.baseURL = 'http://49.235.157.87:9220/'
Vue.prototype.axios = axios

new Vue({
  i18n,
  store,
  router,
  render: h => h(App),
}).$mount('#app')

vuex
import Vue from 'vue'
import Vuex from 'vuex'
import other from './moduls/other'
Vue.use(Vuex)

const state = {
    isLogin: false,
    language: 'zh-CN'
}
const getters = {
    isLogin: state => state.isLogin, // isLogin = function (state) { retrun state.isLogin }
    language: state => state.language
}
const mutations = {
    setIsLogin(state, payload){
        state.isLogin = payload
    },
    setLanguage(state, payload){
        state.language = payload
    }
}
const actions = {
    setIsLogin(state, payload){
        state.commit('setIsLogin', payload)
    },
    setLanguage(state, payload){
        state.commit('setLanguage', payload)
    }
}
const modules = {
    other
}

const store = new Vuex.Store({
    state, getters, mutations, actions, modules
})


export default store
home.vue





你可能感兴趣的:(2019-12-16-vue-i18n-前端国际化)