html引vue怎么实现国际化,vue-i18n实现国际化

需求

如果项目需要国际化,即点击按钮切换 中/英文。那么就需要引入 vue-i18n 插件

安装

首先创建项目

vue init webpack

然后安装 i18n 插件

npm install vue-i18n --save

创建语言包

src/common/lang/en.js

export const lang = {

welcome: 'Welcome to Your Vue.js App',

essential_links: 'Essential Links',

core_docs: 'Core Docs',

forum: 'Forum',

community_chat: 'Community Chat',

twitter: 'Twitter',

docs_for_this_template: 'Docs for This Template',

ecosystem: 'Ecosystem',

vue_router: 'vue-router',

vuex: 'vuex',

vue_loader: 'vue-loader',

awesome_vue: 'awesome-vue'

}

src/common/lang/zh.js

export const lang = {

welcome: '欢迎来到你的Vue.js应用',

essential_links: '基本环节',

core_docs: '核心文档',

forum: '论坛',

community_chat: '社区聊天',

twitter: '推特',

docs_for_this_template: '模板文档',

ecosystem: '生态系统',

vue_router: 'vue路由器',

vuex: 'vue状态管理器',

vue_loader: 'vue文件编译成html文件',

awesome_vue: 'vue图标库'

}

封装插件

src/common/lang/index.js

这里做了3件事

挂载 VueI18n组件到 Vue

将语言列表绑定到 Vue 的 prototype 中,之后就可以在任何地方通过 this 引用该变量了

新建 VueI18n 对象,指定当前语言标识 和 多国语言分别对应的资源列表,然后设置默认导出该变量

import Vue from 'vue'

import VueI18n from 'vue-i18n'

Vue.use(VueI18n) // 挂载i18n

Vue.prototype.language = [{ // 挂载全局变量

value: 'en-US',

text: 'English'

},

{

value: 'zh-CN',

text: '中文'

}

]

const i18n = new VueI18n({

locale: 'en-US', // 语言标识,通过this.$i18n.locale来切换语言

messages: {

'en-US': require('./en'), // 英文语言包

'zh-CN': require('./zh') // 中文语言包

}

})

export default i18n

修改模板

src/main.js

引入封装好的i18n变量,并将其添加到Vue的构造对象中

// The Vue build version to load with the `import` command

// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import Vue from 'vue'

import App from './App'

import router from './router'

import i18n from './common/lang/index'

Vue.config.productionTip = false

/* eslint-disable no-new */

new Vue({

el: '#app',

i18n,

router,

components: { App },

template: ''

})

src/components/HelloWorld.vue

对于绑定到全局里的language列表变量,通过vue的列表功能,将其自动添加到select元素的选项表里面

{{item.text}}

语言列表改变了语言之后,会触发onChange事件,通过修改 this.$i18n.locale 变量可以改变当前页面的语言。

对于需要国际化的变量,需要使用 $t(lang.strId)进行转换,因此需要在 computed 对象中对其进行处理

export default {

name: 'HelloWorld',

data () {

return {

msg: 'welcome'

}

},

methods: {

changeLang (event) {

console.log(event.target.value)

this.$i18n.locale = event.target.value

}

},

computed: {

getMsg: function () {

const str = 'lang.' + this.msg

return this.$t(str)

}

}

}

添加样式,将切换语言的列表固定在页面右上角

position: fixed;

top: 2rem;

right: 4rem;

}

结果展示

01d030643cf0fda305bed96cf5f2986c.png

b30a171af65c8c1158993a939180ca47.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值