方案一
//需要把$t手动挂载到全局
//main.js
app.config.globalProperties.$t = i18n.global.t
//需要使用的时候在组件里引用
import { getCurrentInstance } from 'vue'
const _this = getCurrentInstance().appContext.config.globalProperties
console.log('$i18n',_this.$t('欢迎'))
方案二
legacy设置为false
//main.js
const i18n = createI18n({
locale: localStorage.getItem('i18n-lang'),
fallbackLocale: 'zh',
messages: {
en,
zh
},
legacy: false
})
//组件中先引用再使用
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
console.log('$i18n',t("欢迎"))
方案三
直接像vue2一样,使用选项式写法,可以直接使用
//使用vue选项式写法,可以直接使用this.$t
<script>
export default {
methods:{
change(){
console.log(this.$t('欢迎'))
}
},
mounted() {
this.change()
}
}
</script>