需求:在页面中实现语言的切换。
思路:
- 使用第三方包(vue-i18n),实现语言的切换。
- 将修改后的语言类型保存到 cookie 中,每次打开页面再从 cookie 中取出赋值给 locale,实现语言类型的持久化。
- 修改 element 中的语言。
步骤:
- 多语言插件的使用
- 下载第三方插件包
$ npm i vue-i18n@8.22.2
-
在 src/lang/index.js 创建多语言对象
// 专门用来处理语言包 // 导入 vue import Vue from 'vue' // 导入语言包 import Vuei18n from 'vue-i18n' // 使用插件 Vue.use(Vuei18n) // 暴露一个语言包对象 export default new Vuei18n({ // 定义可选择的语言 messages: { 'en': { 'workcalendar': 'workcalendar' }, 'zh': { 'workcalendar': '工作日历' } }, // 设置使用的语言 locale: 'en' })
-
在 main.js 注册多语言对象
// 导入语言包 import i18n from '@/lang' new Vue({ el: '#app', i18n, // 挂载语言包 router, store, render: h => h(App) })
-
在 目标页面 使用多语言对象
<div class="title"> <!-- 工作日历 --> {{ $t('workcalendar') }} </div>
- 下载第三方插件包
- 语言类型持久化
- 在 views/dashboard/index.vue 中,
- 导入第三方包(cookie)
import Cookie from 'js-cookie'
- 添加一个按钮
<el-col :span="12"> <el-card> <el-button @click="changeLang">点我切换语言</el-button> </el-card> </el-col>
- 实现按钮点击事件(修改语言类型)
// 切换语言 changeLang () { this.$i18n.locale === 'zh' ? (this.$i18n.locale = 'en') : (this.$i18n.locale = 'zh') // 将语言类型保存到本地 Cookie.set('lang', this.$i18n.locale) }
- 导入第三方包(cookie)
-
在 src/lang/index.js 中
-
导入第三方包(cookie)
import Cookie from 'js-cookie'
-
取出语言类型
// 设置使用的语言 locale: Cookie.get('lang') || 'zh'
-
- 在 views/dashboard/index.vue 中,
-
修改 element 中的语言
-
在 lang/index.js 中导入 element 的语言包,并定义语言。
// 导入语言字典 import elementEn from 'element-ui/lib/locale/lang/en' import elementZh from 'element-ui/lib/locale/lang/zh-CN' // 暴露一个语言包对象 export default new Vuei18n({ // 定义可选择的语言 messages: { 'en': { ...elementEn }, 'zh': { ...elementZh } },
-
在 main.js 中使用 element 语言包
// 导入语言包 import i18n from '@/lang' // set ElementUI lang to EN // Vue.use(ElementUI, { locale }) // 如果想要中文版 element-ui,按如下方式声明 Vue.use(ElementUI, { i18n: (key, value) => { return i18n.t(key, value) } })
-
在 views/dashboard/index.vue 中,切换语言后要刷新页面
// 切换语言 changeLang () { this.$i18n.locale === 'zh' ? (this.$i18n.locale = 'en') : (this.$i18n.locale = 'zh') // 将语言类型保存到本地 Cookie.set('lang', this.$i18n.locale) // 刷新页面 this.$router.go(0) }
-