Vue 2项目中如何在alert()内使用vue-i18n的$t翻译方法
Vue 2 + vue-i18n 在JS逻辑中调用翻译的正确方案
错误原因
{{ }} 是Vue专属的模板插值语法,仅能在<template>模板代码内使用,无法直接在组件的JS逻辑代码中生效。
注意:以下写法生效的前提是你已经在项目入口文件中正确注册了vue-i18n实例,且对应的语言包中已经配置了对应文案的翻译条目。
正确实现
在Vue 2组件的实例方法内,直接通过this.$t()调用i18n翻译方法即可,你给出的代码片段修改后如下:
async ChangePassword() { await axios.post('/api/reset-password', this.form).then((response) => { alert(this.$t('Password changed')); }) }
优化建议
你当前的代码同时混用了await和.then两种异步处理方式,属于冗余写法,更简洁的async/await统一写法参考:
async ChangePassword() { try { // 发送重置密码请求 await axios.post('/api/reset-password', this.form) // 弹出翻译后的成功提示 alert(this.$t('Password changed')) } catch (error) { // 可在此处添加错误场景的翻译提示 alert(this.$t('Password change failed')) } }
内容的提问来源于stack exchange,提问作者Domen
相关产品推荐
相关产品推荐

