zoukankan      html  css  js  c++  java
  • uniapp之项目中实现国际化语言

    步骤

    1. 在相对根目录 utils/lang 的文件夹创建js的语言文件。当然,也可以根据实际情况,在其他目录下。这里,使用了两种语言,en-US (英文)和zh-CN(简体中文)。

    2. 打开main.js引入 vue-i18n 和语言包,并根据需要默认其中一种语言。

    import Vue from 'vue'
    import App from './App'
    import enUS from 'utils/lang/en-US.js';        // 英文语言文件
    import zhCN from 'utils/lang/zh-CN.js';        // 中文语言文件
    import VueI18n from 'vue-i18n'  
    
    Vue.use(VueI18n)
    Vue.config.productionTip = false
    
    const i18n = new VueI18n({  
      locale: 'en-US',  
      messages: {  
        'en-US': enUS,  
        'zh-CN': zhCN
      }  
    })  
    
    Vue.prototype._i18n = i18n  
    App.mpType = 'app'
    
    const app = new Vue({
        i18n,
        ...App
    })
    app.$mount()

    3. 当页面中需要引用语言栏时,调用$t方法。

    uniapp 不支持在取值表达式中直接调方法,因此,$t方法不可用,所以通过计算属性的方式。

    因此,要调用语言栏的页面(如index.vue)代码如下:

     1 <template>
     2     <view >
     3         <view>{{ i18n.invite }}</view>
     4         <view>{{ i18n.game }}</view>
     5     </view>
     6 </template>
     7 
     8 <script>
     9     export default {
    10         data() {
    11             return {
    12             }
    13         },
    14         computed: {
    15             i18n() {
    16                 return this.$t('index')
    17             }
    18         },
    19     }
    20 </script>
    21 
    22 <style>
    23     
    24 </style>

    扩展:上面的方式,是否可用定义一个变量,然后获取它的方法?答:可以,但不推荐这么使用。具体的原因,是因为计算属性,有自己合适的应用场景。不推荐的代码示例如下:

     1 <template>
     2     <view >
     3         <view>{{ i18n.invite }}</view>
     4         <view>{{ i18n.game }}</view>
     5     </view>
     6 </template>
     7 
     8 <script>
     9     export default {
    10         data() {
    11             return {
    12                 i18n : null,
    13             }
    14         },
    15         computed: {
    16             
    17         },
    18         onLoad:function(){
    19             this.i18n = this.$t('index');
    20         }
    21         
    22     }
    23 </script>
    24 
    25 <style>
    26     
    27 </style>
    View Code

    切换语言

    以上代码,已经让全局包含_i18n。.vue页面切换语言方法为 this._i18n.locale = "zh-CN";

    参考网址

  • 相关阅读:
    ssh免密登录
    jdk安装
    jq选择器
    使用<button></button>标签
    mysql连接字符串
    如何把maven项目转成web项目
    pl/sql连接远程oracle
    Oracle 存储过程
    SQL Server存储过程
    MySQL存储过程
  • 原文地址:https://www.cnblogs.com/luyj00436/p/15096300.html
Copyright © 2011-2022 走看看