乐闻世界logo
搜索文章和话题

How to use useI18n inside vue3 composition api?

1个答案

1

Using vue-i18n and Vue 3 Composition API

In Vue 3, leveraging the Composition API enables more flexible code construction and organization. For internationalization (i18n), you can integrate the vue-i18n library with the Composition API to implement multilingual functionality. Below are the steps and examples for using vue-i18n within Vue 3's Composition API.

Step 1: Install vue-i18n

First, verify that vue-i18n is installed. If not, install it using npm or yarn:

bash
npm install vue-i18n@next # or yarn add vue-i18n@next

Step 2: Configure the i18n instance

Create an i18n instance and define your translation dictionary. For example, create an i18n.js file:

javascript
import { createI18n } from 'vue-i18n'; const messages = { en: { message: { hello: 'hello world' } }, zh: { message: { hello: '你好,世界' } } }; const i18n = createI18n({ locale: 'en', // Set default language fallbackLocale: 'en', // Set fallback language messages, // Define translation dictionary }); export default i18n;

Step 3: Use i18n in the Vue application

In main.js (or a similar entry file), import the i18n instance and register it as a plugin:

javascript
import { createApp } from 'vue'; import App from './App.vue'; import i18n from './i18n'; const app = createApp(App); app.use(i18n); app.mount('#app');

Step 4: Use useI18n in components

Within Vue 3 components, utilize the useI18n function to integrate i18n functionality. Here's an example component:

vue
<template> <div> {{ t('message.hello') }} </div> </template> <script setup> import { useI18n } from 'vue-i18n'; const { t } = useI18n({ inheritLocale: true, // Inherit global locale settings useScope: 'local' // Optional: 'local' | 'parent' | 'global' }); </script>

In this example, the useI18n function provides the t method for translating key paths. You call t('message.hello') in the template to display the 'hello' message in the current language.

Summary

By following these steps, you can implement multilingual functionality in Vue 3 using vue-i18n with the Composition API. This approach offers greater flexibility and clearer code structure, simplifying internationalization.

2024年8月8日 16:36 回复

你的答案