vue使用插件实现i18n

实现功能:中英文切换响应式,切换语言配置
效果图:
请添加图片描述
/plugins/i18n.ts

import { reactive, ref } from 'vue'
let locale = ref('')
// 直接 let messages = reactive({}) 会丢失响应性
let messages = reactive({
  data: null
})

export function createI18n (options) {
  locale.value = options.locale
  messages.data = options.messages
  return {
    install: (app) => {
      // 注册一个全局可用的 $translate() 方法
      app.config.globalProperties.$translate = (key) => {
        return key.split('.').reduce((o, i) => {
          if (o) return o[i]
        }, messages.data[locale.value])
      }
    }
  }
}

export function changeLocale (lang) {
  locale.value = lang
}

export function changeMessages (msg) {
  messages.data = msg
}
export const currentoptions = {
  locale,
  messages: messages.data
}

main.ts

import { createApp } from 'vue'
import App from './app.vue'
import { createI18n } from '@/plugins/i18n'

const app = createApp(App)
// 配置语言
const language = {
  zh: {
    greetings: {
      hello: '哈喽'
    }
  },
  en: {
    greetings: {
      hello: 'hello'
    }
  }
}
const i18n = createI18n({
  locale: 'zh',
  messages: language
}) // 传入参数以保证语言类型和语言配置的响应式

app
  .use(i18n) // 能使用app.use()说明i18n这个函数直接返回的是插件的install选项
  .mount('#app')

ts中扩展全局属性还需要声明配置,这样才能在Vue全局中使用 $translate
/typings/global-properties.ts

export {}

declare module 'vue' {
  interface ComponentCustomProperties {
    $translate: (key: string) => string
  }
}

使用test.vue

<template>
  <div>
    <button @click="changeLanguage">changeLanguage</button>
    <button @click="changeMsg">changeMsg</button>
    <p>{{ $translate('greetings.hello') }}</p>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
import { changeLocale, currentoptions, changeMessages } from '@/plugins/i18n'

// const translate = getCurrentInstance().appContext.config.globalProperties.$translate
const changeLanguage = () => {
  changeLocale(currentoptions.locale.value === 'zh' ? 'en' : 'zh')
}

const changeMsg = () => {
  const language = {
    zh: {
      greetings: {
        hello: '哈喽22'
      }
    },
    en: {
      greetings: {
        hello: 'hello222'
      }
    }
  }
  changeMessages(currentoptions.messages = language)
}

</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值