vue项目如何实现多语言切换,国际化(i18n)

vue项目如何实现多语言切换,国际化(i18n),第1张

1.下载i18n这个插件

npm i [email protected] (一定要指定版本,不然会报错)

2. 代码配置

  a.可以写在min.js 中,我是新写了一个文件,再引入到min.js中的

 //index.js
import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);

//使用的是sessionStroage中存储的的lang,默认是中文简体cn

const i18n = new VueI18n({
    locale: window.sessionStorage.getItem('lang') || 'cn',//将i18n的locale设置为你需要的语言
    messages: {
        'cn': require("./zh"), //中文简体
        'en': require('./en'),//英文

    },
    //取消警告
    silentTranslationWarn: true,
})
export default i18n

b.目录结构

c.英文版的配置文件

//en.js   英文版
module.exports = {
  home: {
    'home': 'Home',
  },

}

 d.中文的配置文件

//zh.js  中文版文件
module.exports = {
     home: {
          'home': '首页',
      
     },
 
}

 3. min.js中需要引入,并声明


//引入lang.js文件
import i18n from './lang'

new Vue({
  //这里需要声明一下
  i18n,
  render: h => h(App)
}).$mount('#app')

4.页面中使用

//直接使用

{{$t('home.home')}}

, //data中使用 不用加引号

{{$t(text1)}}

, export default { data() { return { text1:'home.home' } },

5.监视i18n的变化

  watch: {
    '$i18n.locale': {
     //当值不发生改变的时候的也可以执行  设置immediate: true
      immediate: true,
      handler(newName, oldName) {
        if (newName === 'cn') {
          this.dataList = [
            "index_1.jpg",
            "index_2.jpg",
            "index_3.jpg",]
        } else if (newName === 'en') {
          this.dataList = [
            "en-index_1.png",
            "en-index_2.png",
            "en-index_3.png",]
        }
      },
    },

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1321197.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存