vue i18n 设置保存到 Cookies

vue i18n 设置保存到 Cookies

安装js-cookie

1
yarn add js-cookie --save

引起

1
import Cookies from 'js-cookie'

i18n文件中设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import * as locale from './locales'
import Cookies from 'js-cookie'

Vue.use(VueI18n)

export default new VueI18n({
locale: Cookies.get('language') || 'en',
messages: {
'en' : locale.enUS,
'zh' : locale.zhCH,
},
})

组件中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<b-navbar>
<b-navbar-nav class="ml-auto">
<b-nav-item-dropdown :text="$t('message.lang')" right>
<b-dropdown-item v-for="(lang, i) in langs" :key="lang.index" @click="setLocalLanguage(lang)">{{ lang }}</b-dropdown-item>
</b-nav-item-dropdown>
</b-navbar-nav>
</b-navbar>
</template>
<script>
import Cookies from 'js-cookie'
export default {
data() {
return {
langs : ['en', 'zh'],
}
},
methods:{
setLocalLanguage(lang) {
this.$i18n.locale = lang
Cookies.set('language', lang)
}
},

}
</script>