使用 vue-i18n 切换中英文

使用 vue-i18n 切换中英文

vue-i18n 仓库地址:https://github.com/kazupon/vue-i18n

兼容性:

支持 Vue.js 2.x 以上版本

 

安装方法:(此处只演示 npm)

npm install vue-i18n

 

使用方法:

1、在 main.js 中引入 vue-i18n (前提是要先引入 vue)

import VueI18n from 'vue-i18n'Vue.use(VueI18n)

 

2、准备本地的翻译信息

复制代码
const messages = {zh: {message: {hello: '好好学习,天天向上!'}},en: {message: {hello: 'good good study, day day up!'}}
}
复制代码

 

3、创建带有选项的 VueI18n 实例

const i18n = new VueI18n({locale: 'en', // 语言标识
    messages
})

 

4、把 i18n 挂载到 vue 根实例上

const app = new Vue({router,i18n,...App
}).$mount('#app')

 

5、在 HTML 模板中使用

<div id="app"><h1 style="font-size: 16px; text-align: center;">{{ $t("message.hello") }}</h1></div>

 

查看运行效果:

我们刚才选定的语言标识是 “en” 英语,现在改成 “zh” 中文,并查看效果

const i18n = new VueI18n({locale: 'zh', // 语言标识
    messages
})

这样就可以轻松实现国际化了,实际开发中,页面内容肯定是很多的,我们可以把对应语言的信息保存为不同的 json对象

复制代码
const i18n = new VueI18n({locale: 'en',  // 语言标识
    messages: {'zh': require('./common/lang/zh'),'en': require('./common/lang/en')}
})
复制代码

zh.js

复制代码
// 注意:一定是 exports,不是 export,否则会报错,报错信息是下列的中的内容不是 string
module.exports = {message: {title: '运动品牌'},placeholder: {enter: '请输入您喜欢的品牌'},brands: {nike: '耐克',adi: '阿迪达斯',nb: '新百伦',ln: '李宁'}
}
复制代码

en.js

复制代码
module.exports = {message: {title: 'Sport Brands'},placeholder: {enter: 'Please type in your favorite brand'},brands: {nike: 'Nike',adi: 'Adidas',nb: 'New Banlance',ln: 'LI Ning'}
}
复制代码

接下来,在HTML 模板中使用,要特别注意在 js 中的国际化写法

复制代码
// HTML
<div id="app"><div style="margin: 20px;"><h1>{{$t("message.title")}}</h1><input style="width: 300px;" class="form-control" :placeholder="$t('placeholder.enter')"><ul><li v-for="brand in brands">{{brand}}</li></ul></div>
</div>// JS
data () {return {brands: [this.$t('brands.nike'), this.$t('brands.adi'), this.$t('brands.nb'), this.$t('brands.ln')]}},
复制代码

查看编译效果:

现在换成英文的:

在上面的操作中,我们都是通过手动修改 locale 的属性值来切换语言,实际上,更希望浏览器自动识别,这里可以借助于 cookie

1、新建一个 cookie.js 文件,用于读取cookie

复制代码
function getCookie(name,defaultValue) {var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");if (arr = document.cookie.match(reg))return unescape(arr[2]);elsereturn defaultValue;
}export {getCookie
}
复制代码

2、在 main.js 中引入这个js,并通过 PLAY_LANG 属性来获取浏览器的语言

复制代码
const i18n = new VueI18n({locale: getCookie('PLAY_LANG','zh'),    // 语言标识
    messages: {'zh': require('./common/lang/zh'),'en': require('./common/lang/en')}
})
复制代码

这里需要注意两个极易出错的地方:

(1)、将 $t() 写成了 $()

(2)、json 中在同一个对象里有同名属性

 

vue-i18n 提供了一个全局配置参数叫 “locale”,通过改变 locale 的值可以实现不同语种的切换

下面的案例借用了 Element UI 的弹窗样式,上面的步骤不再赘述,直接上核心代码

// template
<h2>{{$t('test')}}</h2>
<button type="button" class="btn btn-success" @click="changeLocale">中文/EN</button>        
复制代码
// js方法
changeLocale () {this.$confirm(this.$t('layer.toggle'), this.$t('layer.tips'), {confirmButtonText: this.$t('button.ok'),cancelButtonText: this.$t('button.cancel'),type: 'warning'}).then(() => {let locale = this.$i18n.localelocale === 'zh' ? this.$i18n.locale = 'en' : this.$i18n.locale = 'zh'}).catch(() => {this.$message({type: 'info',})      })
},
复制代码

效果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/387138.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ZooKeeper数据模型

Zookeeper的数据模型 层次化的目录结构&#xff0c;命名符合常规文件系统规范&#xff08;Linux&#xff09; 每个节点在zookeeper中叫做znode,并且其有一个唯一的路径标识 节点Znode可以包含数据和子节点(即子目录)&#xff0c;但是EPHEMERAL类型的节点不能有子节点 Znod…

堆叠条形图

堆叠条形图 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.dates as mdates#解决能显示中文 mpl.rcParams[font.sans-serif][SimHei] #指定默认字体 SimHei为黑体 mpl.rcParams[axes.unicode_minus]Fal…

spring boot 服务器常用

ps aux|grep tgcwll /opt/nginx/html sudo cp -r /tmp/tgcw/dist/* /opt/nginx/html/design sudo cp -r /tmp/tgcw/dist/* /opt/nginx/html springboot 启动nohup java -jar tgcw-service-usermanagement-0.0.1-SNAPSHOT.jar --spring.profiles.activedemo > /dev/null 2&g…

PHP数组 转 对象/对象 转 数组

/*** 数组 转 对象** param array $arr 数组* return object*/ function array_to_object($arr) {if (gettype($arr) ! array) {return;}foreach ($arr as $k > $v) {if (gettype($v) array || getType($v) object) {$arr[$k] (object)array_to_object($v);}}return (obj…

ZooKeeper編程01--RMI服務的多服務器管理

服務器端與客戶端都要用到&#xff1a; public interface ZkInfo {String ZK_CONNECTION_STRING "192.168.1.201:2181,192.168.1.202:2181,192.168.1.203:2181";int ZK_SESSION_TIMEOUT 5000;String ZK_REGISTRY_PATH "/registry";String ZK_PROVIDER_…

org.activiti.engine.ActivitiOptimisticLockingException updated by another transaction concurrently

org.activiti.engine.ActivitiOptimisticLockingException: Task[id5905010, name审核(市场部)] was updated by another transaction concurrentlyat org.activiti.engine.impl.db.DbSqlSession.flushUpdates(DbSqlSession.java:872)at org.activiti.engine.impl.db.DbSqlSess…

DataTable不能通过已删除的行访问该行的信息解决方法

使用dt.Rows[0]["name", DataRowVersion.Original]可以获取转载于:https://www.cnblogs.com/heyiping/p/10616640.html

ZooKeeper編程02--多線程的分佈式鎖

面向過程版&#xff1a; package distributedLockProcess;import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch;import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zoo…

01 Python变量和数据类型

Python变量和数据类型 1 数据类型 计算机&#xff0c;顾名思义就是可以做数学计算的机器&#xff0c;因此&#xff0c;计算机程序理所当然也可以处理各种数值。 但是&#xff0c;计算机能处理的远不止数值&#xff0c;还可以处理文本、图形、音频、视频、网页等各种各样的数…

初识Python-1

1&#xff0c;计算机基础。 2&#xff0c;python历史。 宏观上&#xff1a;python2 与 python3 区别&#xff1a; python2 源码不标准&#xff0c;混乱&#xff0c;重复代码太多&#xff0c; python3 统一 标准&#xff0c;去除重复代码。 3&#xff0c;python的环境。 编译型&…

02 List、Tuple、Dict、Set

List 线性表 创建List&#xff1a; >>> classmates [Michael, Bob, Tracy] >>> L [Michael, 100, True] #可以在list中包含各种类型的数据 >>> empty_list [] #空List 按索引访问List&#xff1a; >>> print L[0] #索引从0开始…

Jenkins的一些代码

pipeline {agent anyenvironment { def ITEMNAME "erp"def DESTPATH "/home/ops/testpipe"def codePATH"/var/lib/jenkins/workspace/test_pipeline"}stages { stage(代码拉取){steps {echo "checkout from ${ITEMNAME}"git url:…

利用layui前端框架实现对不同文件夹的多文件上传

利用layui前端框架实现对不同文件夹的多文件上传 问题场景&#xff1a; 普通的input标签实现多文件上传时&#xff0c;只能对同一个文件夹下的多个文件进行上传&#xff0c;如果要同时上传两个或多个文件夹下的文件&#xff0c;是无法实现的。这篇文章就是利用layui中的插件&am…

ps、grep和kill联合使用杀掉进程

ps、grep和kill联合使用杀掉进程例如要杀掉hello这个进程&#xff0c;使用下面这个命令就能直接实现。ps -ef |grep hello |awk {print $2}|xargs kill -9这里是输出ps -ef |grep hello 结果的第二列的内容然后通过xargs传递给kill -9,其实第二列内容就是hello的进程号&#xf…

03 控制語句

if语句 if age > 18 print your age is, age else print teenager Python代码的缩进规则&#xff1a;具有相同缩进的代码被视为代码块。 if age > 18 print adult elif age > 6 print teenager elif age > 3 print kid else print baby for循环 L [Adam, L…

yum 来安装 nodejs

要通过 yum 来安装 nodejs 和 npm 需要先给 yum 添加 epel 源&#xff0c;添加方法在 centos 添加epel和remi源 中##添加 epel 源 64位: rpm -ivh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm32位: rpm -ivh http://download.fedoraproj…

yzh的神仙题

U66905 zz题 考虑一个点权值被计算了多少次。。。不知 所以对未来承诺&#xff0c;方便直接算上总数&#xff01; 然后其实是给边定向&#xff0c;即先删除fa和son的哪一个 f[x][j]&#xff0c;会计算j次 无法转移 f[x][j][k]&#xff0c;其中会从子树计算k次。 当边从儿子指向…

04 函數

內置函數 Python內置了很多有用的函數&#xff0c;可以直接調用。 要調用一個函數&#xff0c;需要知道函數的名稱和參數。 可以直接從Python的官方網站查看文檔&#xff1a;http://docs.python.org/2/library >>> abs(-20) >>> help(abs) >>>…

iview render的时候可以写控件的基本格式

render: (h, params) > {return h(div, [h(Button, {props: {type: id,size: small},style: {marginRight: 5px},on: {click: () > {this.pojectshow(this.datatable[params.index].id)}}}, 详情),h(Button, {props: {type: id,size: small},style: {marginRight: 5px},o…

ES6基本使用

var let 度可用于声明变量. 区别&#xff1a;1、let&#xff1a;只在let命令所在代码块内有效 2、let 不存在变量提升&#xff08;内部影响不到外部&#xff09; var b [];for(var j0;j<10;j){let dj;b[j]function(){console.log(d);};}b[3]() //3 3、let 不允许在相同作用…