基本信息
文件名称:vue多语言转换的几种方法总结.docx
文件大小:16.5 KB
总页数:4 页
更新时间:2025-05-21
总字数:约1.91千字
文档摘要

vue多语言转换的几种方法总结

目录一、静态转换使用方式二、vue-i18n按字查询替换使用总结

一、静态转换

使用Vue插件language-tw-loader在打包时把本地的文字转换成繁体,动态加载的文字不会转换。也就是说接口返回的文字不会自动转换。打包后无法再切换为简体。除非专门打一个简体的包。

使用方式

1、安装插件

npmilanguage-tw-loader--save

2、修改webpack配置文件webpack.base.conf.js

module:{

rules:[

test:/\.(js|vue)$/,

loader:language-tw-loader,

}

3、打包或者运行

npmrundev

此方法不适用于vue-cli3

二、vue-i18n按字查询替换

1、安装

npminstallvue-i18n

2、然后在我们的项目中的statics文件夹下面添加i18n文件夹,然后在文件夹中新建我们的json格式的语言包目录大致为:

en.js

module.exports={

login:{

title:thistitle,

username:Pleaseentertheusername,

password:Pleaseenteryourpassword,

}

zh.js

module.exports={

login:{

title:标题,

username:请输入用户名,

password:请输入密码,

}

在i18n.js中引入i18n和语言包

importVuefromvue

importVueI18nfromvue-i18n

Vue.use(VueI18n)

//以下为语言包单独设置的场景,单独设置时语言包需单独引入

constmessages={

zh_CN:require(../statics/i18n/zh),//中文语言包

en_US:require(../statics/i18n/en)//英文语言包

//最后exportdefault,这一步肯定要写的。

exportdefaultnewVueI18n({

locale:en,//setlocale默认显示英文

messages:messages//setlocalemessages

})

然后在main.js中挂载至入口文件

-main.js

//注意,因为我们index.js中把i18n绑定到了window,所以要在第一个引入

importi18nfrom./locales

importVuefromvue

importAppfrom./App.vue

import./common.scss

constapp=newVue({

components:{

i18n,

render:h=h(App),

});

使用

template

divid=pageDiv

section

h3{{$t(login.title)}}/h3

button@click=langToggle切换语言/button

/section

/div

/template

script

exportdefault{

data(){

return{

methods:{

langToggle(){

if(this.$i18n.locale==zh_CN){

this.$i18n.locale=en_US;

}else{

this.$i18n.locale=zh_CN;

console.log(this.$i18n.locale)

mounted(){

created(){

/script

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。