1:下载vue-i18n插件
npm install vue-i18n
2:创建中英文js文件
在文件中写入需要翻译的内容
中文版cn.js
export const m = {
help: "帮助",
homeSearch: "请输入",
}
英文版en.js
export const m = {
help: "help",
homeSearch: "Please input",
}
3:配置main.js文件
//引入中英文切换插件vue-i18n
import VueI18n from 'vue-i18n'
Vue.use(VueI18n) // 挂载
const i18n = new VueI18n({
locale: 'zh-CN', // 语言标识
messages: {
'zh-CN': require('./utils/i18n/langs/cn'), // 中文版cn.js文件路径
'en-US': require('./utils/i18n/langs/en') // 英文版en.js文件路径
}
})
new Vue({
el: '#app',
render:h=>h(App),
router,
store,
i18n, // !!!!!一定要引入
})
4:语言切换组件
html代码
<el-dropdown trigger="click" @command="setLanguage" @visible-change="visibleChange">
<span class="el-dropdown-link">
<el-button type="primary" size="small" class="languageBtn"><span>{{translate}}</span><i :class="languageIcon"></i></el-button>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="en">English</el-dropdown-item>
<el-dropdown-item command="cn">中文</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
js代码
data() {
translate: "中文",
languageIcon: "el-icon-caret-bottom"
},
methods() {
setLanguage(name) {
if (name === "cn") {
this.translate = "中文"
this.$i18n.locale = 'zh-CN' // 切换为中文
this.$message.success('已切换中文');
} else {
this.translate = "English"
this.$i18n.locale = 'en-US' // 切换为英文
this.$message.success('Chinese switched');
}
},
visibleChange(value) {
if(value){
this.languageIcon = "el-icon-caret-top"
} else {
this.languageIcon = "el-icon-caret-bottom"
}
}
}
5:数据渲染
使用方式一:
<el-button
type="primary"
icon="el-icon-plus"
>{{$t('m.help')}}</el-button>
使用方式二:
<el-input
v-model="value"
:placeholder="$t('m.homeSearch')"
></el-input>
6:看效果
参考https://blog.csdn.net/m0_46627730/article/details/107590852