vue实现中英文切换

it2023-01-23  49

1、通过npm安装vue-i18n

npm install vue-i18n --save-dev

2、创建cn.js和en.js文件

//cn.js module.exports = { user: { msg: '生活的道路一旦选定,就要勇敢知地走到底,决不回头。' } } //en.js module.exports = { user: { msg: 'Once the road of life is chosen, we should go to the end bravely and never look back.' } }

3、建立js文件,将cn.js和en.js引入

import Vue from 'vue' import VueI18n from 'vue-i18n' import en from './en.js' import cn from './cn.js' Vue.use(VueI18n) const messages = { en: Object.assign(en), cn: Object.assign(cn) } const i18n = new VueI18n({ locale: localStorage.getItem('locale') || 'cn', messages }) export default i18n

4、在main.js中引用

import i18n from './assets/js/i18n' new Vue({ i18n, }).$mount('#app')

5、使用vue-i18n

<template> <div> <div class="tab"> <button @click="toggleLang('cn')" :disabled="$i18n.locale == 'cn'">ZH</button> | <button @click="toggleLang('en')" :disabled="$i18n.locale == 'en'">EN</button> </div> <div> <p>{{$t('user.msg')}}</p> </div> </div> </template> <script> export default { name: 'Contact', methods: { toggleLang(lang) { if (lang == 'cn') { localStorage.setItem('locale', 'cn') this.$i18n.locale = localStorage.getItem('locale') this.$store.commit("setlang", "cn"); }else if (lang == 'en') { localStorage.setItem('locale', 'en') this.$i18n.locale = localStorage.getItem('locale') this.$store.commit("setlang", "en"); } } } } </script>

Object.assign()方法仅将可枚举和拥有的属性从源对象复制到目标对象。 Object.assign()

Github地址

Github地址:https://github.com/kazupon/vue-i18n
最新回复(0)