# vue-i18n-demo **Repository Path**: chen_harvey/vue-i18n-demo ## Basic Information - **Project Name**: vue-i18n-demo - **Description**: vue-i18n的简单使用 - **Primary Language**: JavaScript - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-05-12 - **Last Updated**: 2023-05-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README 介绍 | Vue I18n (https://kazupon.github.io/vue-i18n/zh/introduction.html) ## 安装: ``` #npm npm install vue-i18n #yarn yarn add vue-i18n ``` ## 新建lang文件夹,新建index.ts ``` // lang/index.ts import { createI18n } from "vue-i18n"; import zh from './zh' import en from './en' const defaultLocale = localStorage.getItem('locale') || 'zh' const i18n = createI18n({ locale: defaultLocale, allowComposition: true, globalInjection: true, silentFallbackWarn: true, silentTranslationWarn: true, //去除警告信息 messages: { en: en, zh: zh } }) export default i18n ``` ## 新建语言包文件zh.ts 和 en.ts ``` // en.ts export default { nNation: 'EN', world: 'world', say: 'hello', "navbar.action.locale": '切换成中文', } // zh.ts export default { nNation: 'ZH', world: '世界', say: '你好', "navbar.action.locale": 'Switch to Englisth', } ``` ## 创建一个可以切换语言的hook方法, 新建hooks文件夹,新建uselocale.ts ``` // hooks/uselocale.ts import { computed } from "vue"; import { useI18n } from "vue-i18n"; export default function useLocale() { const i18n = useI18n();//实例化i18n const currentLocale = computed(() => { return i18n.locale.value // 固定写法 获取当前语言设置 }) // 切换语言 const changeLocale = (value: string) => { i18n.locale.value = value;//赋值切换语言 localStorage.setItem('locale', value);//修改本地存储 window.alert(i18n.t('navbar.action.locale')) //提示信息 } return { i18n, currentLocale, changeLocale } } ``` ## 在main.ts中引用 ``` // main.ts import { createApp } from 'vue' import './style.css' import App from './App.vue' import i18n from "./lang/index" createApp(App).use(i18n).mount('#app') ``` ## 一个简单的小例子使用 ``` ```