实现中英文翻译切换以及cookie 存储
需要安装以下依赖
npm install vue-i18n --save
npm install js-cookie --save
main.js 内 注入i18n
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'
Vue.use(ElementUI)
Vue.use(VueI18n)
//使用语言包
const i18n = new VueI18n({
locale: Cookies.get('language') || 'zh',
messages:{
en:require("@/assets/i18n/langs/en.js"), //英文文件路径
zh:require("@/assets/i18n/langs/zh.js"), //中文文件路径
},
silentTranslationWarn: true
})
Vue.config.productionTip = false
new Vue({
router,
store,
i18n,
render: h => h(App)
}).$mount('#app')
新建 中英文js文件
zh.js
module.exports = {
navBar:{
home:"首页",
name:"张三"
}
}
en.js
module.exports = {
navBar:{
home:"HOME",
name:"zhangsan"
}
}
需要引入翻译的文件 实例代码:
<template>
<div id="translate" class="translate">
<p>{{ $t('navBar.home')}}</p>
<p>{{ $t('navBar.name')}}</p>
<el-button
@click="changeLaguages"
type="default"
>切换语音</el-button>
</div>
</template>
<script type="text/javascript">
import Cookies from 'js-cookie'
export default {
name: "translate",
data() {
return {
lang: Cookies.get('language') || 'zh',
}
},
components: {
},
methods:{
changeLaguages () {
console.log(this.$i18n.locale)
let lang = this.$i18n.locale === 'zh' ? 'en' : 'zh'
this.$i18n.locale = lang;
Cookies.set("language",lang)
}
}
}
</script>
<style lang="less" scoped>
p{
padding: 10px 0;
}
</style>
发布者:admin,转转请注明出处:http://www.yc00.com/web/1754783866a5201788.html
评论列表(0条)