手把手教你在Vue中使用国际化

目录

1、i18n

        1.1、i18n的安装

2、i18n的使用

        2.1、文件架构

        2.2、语言配置

        2.3、模块化配置

        2.4、在man.js中引入模块化

        2.5、i18n语法


1、i18n

1.1、i18n的安装

i18ninternationalization这个单词的缩写,取了首字母i和结尾字母n,中间一用有18个字母,所以组合起来就所写成i18n,这是一个用于给vue国际化的插件, 它可以轻松地将一些本地化功能集成到你的 Vue.js 应用程序中

//使用yarn
yarn add vue-i18n 
//npm
npm i vue-i18n -S

2、i18n的使用

2.1、文件架构

src目录下创建i18n文件夹,将语言配置(json文件)写入config文件夹中,index.js负责模块化的配置。

2.2、语言配置

src/i18n/config/en.json

{   
    "table": {//表格信息
        "date": "Date",
        "name": "Name",
        "address": "Address"
    },
    "language": {//语言切换时按钮跟着切换
        "Chinese": "Chinese",
        "English": "English"
    }
}

src/i18n/config/zh.json

{   
    "table": {//表格信息
        "date": "时间",
        "name": "姓名",
        "address": "地址"
    },
     "language": {//语言切换时按钮跟着切换
        "Chinese": "中文",
        "English": "英文"
    }
}

2.3、模块化配置

src/i18n/index.js

import Vue from "vue"
import VueI18n from "vue-i18n"
Vue.use(VueI18n)//注入到所有的子组件
​
//require.context(path,deep,regExp)
//有3个方法 分别是keys() 
​
​
let langFileds = require.context('./config', false, /\.js$/)
​
let regExp = /(.*\/)*([^.]+).*/ //正则用于匹配
​
// regExp.exec('./en.js')
​
let messages = {} //声明一个数据模型,对应i18n中的message属性
​
langFileds.keys().forEach(key => {
    let prop = regExp.exec(key)[1] //正则匹配文件名(en|zh这样的值)
    //messages[prop]相当于 messages['en'] = {table:{...}}
    messages[prop] = langFileds(key).default
​
})
console.log(messages);
console.log(langFileds('./en.js'));
​
let locale = localStorage.getItem('lang') || "zh" //从localstorag中获取,初始化语言
​
export default new VueI18n({
    locale,//指定语言字段
    messages,//定义语言字段
    silentTranslationWarn:true//去除警告
})

2.4、在man.js中引入模块化

src/main.js

import Vue from 'vue'
import App from './App.vue'
import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
​
import i18n from "./i18n"
​
new Vue({
  render: h => h(App),
  i18n //挂载
}).$mount('#app')

2.5、i18n语法

按照上面的步骤配置完成后,Vue会多出两个属性$i18n以及$t,$i18n中的属性就是我们在模块化配置i18n的时候暴露的属性,我们可以通过这个属性的locale属性对语言进行切换(即:this.$i18n.locale)。而$t则是可以从语言文件(如:zh.json)中通过键值读取。

<template>
    <div>
        <h1>{
   
   { $t('table.date') }}</h1>
        <select
           @change="handleChange()"
           v-model="language">
            <option value='Chinese'>{
   
   { $t('language.Chinese') }}</option>
            <option value='English'>{
   
   { $t('language.English') }}</option>
        </select>
    </div>
</template>
​
<script>
export default {
    name:'lang',
    data(){
        return {
            language:'Chinese'
        }
    },
    methods: {
        handleChange(){
            this.$i18n.locale = this.language
        }
    },
}
</script>

参考文章:知乎-教你如何在vue中使用国际化

猜你喜欢

转载自blog.csdn.net/qq_52013792/article/details/125509432