需求:
  点击中文按钮,列表显示中文;点击english按钮,列表显示英文

如下图,
在这里插入图片描述
在这里插入图片描述

搭建vue3项目


//使用vite
npm init @vitejs/app

安装国际化依赖插件


npm install vue-i18n@next

创建i18n文件夹


  • src/i18n/ch.ts
export default {
  message:{
    one:'一',
    two:'二'
  }
}
  • src/i18n/en.ts
export default {
  message:{
    one:'one',
    two:'two'
  }
}
  • src/i18n/index.ts
import en from './en'
import ch from './ch'

export default {
  en,
  ch
}
  • src/i18n/i18n.ts
import { createI18n } from "vue-i18n";
import messages from './index'
const language = (
  (navigator.language ? navigator.language : navigator.userLanguage) || 'zh'
).toLowerCase()
const i18n = createI18n({
  fallbackLocale: 'ch',
  globalInjection: true,
  legacy: false,
  locale: language.split("-")[0] || 'zh',
  messages
})

export default i18n

组件内引用


  • main.ts
import { createApp } from 'vue'
import App from './App.vue'
import i18n from './i18n/i18n' //引入i18n

const app = createApp(App)
app.use(i18n) //挂载到vue上

app.mount('#app')
  • 组件内
<template>
  <div>
    <button @click="change('zh')">中文</button>
    <button @click="change('en')">english</button>
  </div>
  <div>
    <ul>
      <li v-for="item in items" :key="item.label">{{ t(`message.${item.label}`) }}</li>
    </ul>
  </div>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const { t } = useI18n()
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
function change(type: string) {
  proxy.$i18n.locale = type
}
const items = [
  { label: 'one' },
  { label: 'two' }
]
</script>
Logo

前往低代码交流专区

更多推荐