美文网首页
2021-10-20 国际化 异步请求后台数据

2021-10-20 国际化 异步请求后台数据

作者: jinya2437 | 来源:发表于2021-10-20 09:41 被阅读0次

src/locales/lang/index.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import axios from 'axios'
import { Message } from 'element-ui'

Vue.use(VueI18n)

/**
 * 请求后台接口获取语言包
 * @param type
 * @returns {AxiosPromise}
 */
function getLang(type) {
  return axios({
    headers:{
      'Accept-Language':type
    },
    method: 'get',
    url: `${process.env.VUE_APP_BASE_API}/Base/Language/GetLangResource?lang=${type}`
  })
}


let i18n = new VueI18n({
  silentTranslationWarn: true,
  locale: 'zh-CN',
  messages:{}
})
//  异步请求语言包并且赋值到i18n中
async function loadLanguageAsync(lang) {
  let res = await getLang(lang)
  if(!res.data.Success) {
    Message({type:'error',message:res.data.Msg})
    return
  }

  i18n.setLocaleMessage(lang, res.data.Data)
  i18n.locale = lang
}

// 挂载在VUE原型链上
Vue.prototype.$loadLanguageAsync = loadLanguageAsync


export default i18n

//App.vue文件,页面初始化时
 created() {
    // 请求语言为中文
    this.$loadLanguageAsync('zh-CN')
  },
// select下拉切换语言
 changeLang(lang) {
    this.$loadLanguageAsync(lang)
 }

相关文章

网友评论

      本文标题:2021-10-20 国际化 异步请求后台数据

      本文链接:https://www.haomeiwen.com/subject/maxtaltx.html