关于vue.js:vuevant多语言国际化

3次阅读

共计 950 个字符,预计需要花费 3 分钟才能阅读完成。

1. 开发环境 vue+vant
2. 电脑系统 windows10 专业版
3. 在开发的过程中, 咱们可能会须要适配多国语言, 上面我来分享一下我的办法, 心愿对你有所帮忙。
4. 废话不多说, 间接上操作:

// 在终端 (管理员身份)
npm install vue-i18n --save

5. 我的项目目录构造:

6. 在 src 下新建 i18n 文件夹, 在新建 i18n.js 并增加代码如下:

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from './langs'

Vue.use(VueI18n)
const i18n = new VueI18n({
 locale: localStorage.lang || 'cn',
 messages
})

export default i18n

7. 在 i18n 文件夹下新建 langs 文件夹, 新建 cn.js, 代码如下:

const cn = {
    message: {'hello': '你好,世界',}
}

export default cn

8. 在 i18n 文件夹下新建 langs 文件夹, 新建 en.js, 代码如下:

//en.js
const en = {
    message: {'hello': 'hello, world',}
}

export default en

8-1. 在 i18n 文件夹下新建 langs 文件夹, 新建 index.js, 代码如下:

import en from './en'
import cn from './cn'
export default {
  en,
  cn
} 

9. 在 main.js 中增加如下代码:

import i18n from '@/i18n/i18n';

new Vue({
 router,
 store,
 i18n,
 render: h => h(App)
}).$mount("#app");

10. 如何在 vue 模板中应用呢?

<p>{{$t('message.hello')}}</p> // hello, world

11. 如何切换语言呢?

data() {
    return {lang: 'en'}
},
methods: {switchLang()  {this.$i18n.locale = this.lang}
}
 通过扭转 this.$i18n.locale 的值就能够主动切换页面的语言了 

12. 本期的分享到了这里就完结啦, 心愿对你有所帮忙, 让咱们一起致力走向巅峰。

正文完
 0