### Install vue-i18n-loader
Source: https://vue-i18n.intlify.dev/guide/advanced/sfc
Installation commands for the vue-i18n-loader package required for Quasar CLI projects.
```bash
npm install @intlify/vue-i18n-loader -D
```
```bash
yarn add @intlify/vue-i18n-loader -D
```
```bash
pnpm add -D @intlify/vue-i18n-loader
```
--------------------------------
### Component Resource Localization Example with useI18n
Source: https://vue-i18n.intlify.dev/api/composition
An example demonstrating how to use the `useI18n` hook within a Vue component's setup function for component-specific localization, including language selection.
```html
message: {{ t('hello') }}
```
--------------------------------
### Registering the i18n plugin with Vue
Source: https://vue-i18n.intlify.dev/guide/essentials/started
Illustrates the process of registering the i18n instance as a Vue plugin using the app.use method before mounting the application.
```javascript
const app = createApp(Vue)
app.use(i18n)
app.mount('#app')
```
--------------------------------
### Integrate Vue I18n with Vue App
Source: https://vue-i18n.intlify.dev/guide/installation
After installing vue-i18n, you must explicitly use it with your Vue application instance via `app.use()`. This snippet demonstrates the basic setup for creating and mounting a Vue app with vue-i18n.
```js
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
// something vue-i18n options here ...
})
const app = createApp({
// something vue options here ...
})
app.use(i18n)
app.mount('#app')
```
--------------------------------
### Install unplugin-vue-i18n
Source: https://vue-i18n.intlify.dev/guide/advanced/sfc
Installation commands for the unplugin-vue-i18n package using various Node.js package managers.
```bash
npm install @intlify/unplugin-vue-i18n -D
```
```bash
yarn add @intlify/unplugin-vue-i18n -D
```
```bash
pnpm add -D @intlify/unplugin-vue-i18n
```
--------------------------------
### Create Vue I18n Instance (Composition API)
Source: https://vue-i18n.intlify.dev/api/general
This example shows how to create a Vue I18n instance for the composition API. It requires setting `legacy: false` and specifies the locale and messages. The instance is then used to install Vue I18n, and the `useI18n` composable can be utilized within the component's setup.
```javascript
import { createApp } from 'vue'
import { createI18n, useI18n } from 'vue-i18n'
// call with I18n option
const i18n = createI18n({
legacy: false, // you must specify 'legacy: false' option
locale: 'ja',
messages: {
en: { ... },
ja: { ... }
}
})
const App = {
setup() {
// ...
const { t } = useI18n({ ... })
return { ... , t }
}
}
const app = createApp(App)
// install!
app.use(i18n)
app.mount('#app')
```
--------------------------------
### Accessing Vue I18n via CDN
Source: https://vue-i18n.intlify.dev/guide/essentials/started
Demonstrates how to access Vue and Vue I18n functionality when using global builds via CDN instead of module bundlers.
```javascript
const { createApp } = Vue
const { createI18n, useI18n } = VueI18n
```
--------------------------------
### Configure Bundler Plugins for I18n
Source: https://vue-i18n.intlify.dev/guide/advanced/sfc
Configuration examples for integrating the i18n plugin into Vite and Webpack build pipelines.
```javascript
// vite.config.ts
import { defineConfig } from 'vite'
import { resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'
export default defineConfig({
plugins: [
VueI18nPlugin({
include: resolve(dirname(fileURLToPath(import.meta.url)), './path/to/src/locales/**'),
}),
],
})
```
```javascript
// webpack.config.js
const path = require('path')
const VueI18nPlugin = require('@intlify/unplugin-vue-i18n/webpack')
module.exports = {
plugins: [
VueI18nPlugin({
include: path.resolve(__dirname, './path/to/src/locales/**'),
})
]
}
```
--------------------------------
### Creating and configuring the i18n instance
Source: https://vue-i18n.intlify.dev/guide/essentials/started
Shows how to initialize the Vue I18n instance using createI18n, defining the current locale, fallback locale, and message translation objects.
```javascript
const i18n = createI18n({
locale: 'ja',
fallbackLocale: 'en',
messages: {
en: {
message: {
hello: 'hello world'
}
},
ja: {
message: {
hello: 'こんにちは、世界'
}
}
}
})
```
--------------------------------
### Localizing templates with $t API
Source: https://vue-i18n.intlify.dev/guide/essentials/started
Demonstrates how to use the $t translation API within a Vue Single-File Component to display localized messages.
```vue
{{ $t('message.hello') }}
```
--------------------------------
### Global Import via CDN
Source: https://vue-i18n.intlify.dev/guide/installation
Include Vue I18n globally using CDN links from unpkg.com. This method is suitable for direct HTML script inclusions and provides the latest release or a specific version.
```html
```
--------------------------------
### Install Vue I18n using Package Managers
Source: https://vue-i18n.intlify.dev/guide/installation
Install the latest version of vue-i18n (v11) using popular package managers like npm, yarn, or pnpm. Ensure you are using Vue.js version 3.0.0 or higher.
```sh
npm install vue-i18n@11
```
```sh
yarn add vue-i18n@11
```
```sh
pnpm add vue-i18n@11
```
--------------------------------
### Install Core Base Dependencies
Source: https://vue-i18n.intlify.dev/guide/advanced/lite
Commands to install the required @intlify/core-base package for advanced i18n features.
```npm
npm install --save @intlify/core-base@next
```
```yarn
yarn add @intlify/core-base@next
```
```pnpm
pnpm add @intlify/core-base@next
```
--------------------------------
### Manage global locale state
Source: https://vue-i18n.intlify.dev/guide/advanced/composition
Provides examples of switching the application locale globally using the useI18n hook or template bindings.
```vue
```
--------------------------------
### Core Translation Example (JavaScript)
Source: https://vue-i18n.intlify.dev/api/general
An example illustrating the use of the translate function from '@intlify/core' or '@intlify/core-base'. It shows how to pass context, a translation key, and message values to retrieve translated strings.
```javascript
translate(context, 'foo.bar', ['dio'])
```
--------------------------------
### Create Vue I18n Instance (Legacy API)
Source: https://vue-i18n.intlify.dev/api/general
This example demonstrates how to create a Vue I18n instance using the legacy API mode. It requires specifying the locale and messages. The created instance is then used to install Vue I18n into the Vue application.
```javascript
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
// call with I18n option
const i18n = createI18n({
locale: 'ja',
messages: {
en: { ... },
ja: { ... }
}
})
const App = {
// ...
}
const app = createApp(App)
// install!
app.use(i18n)
app.mount('#app')
```
--------------------------------
### Use useI18n in Vue Components
Source: https://vue-i18n.intlify.dev/guide/advanced/composition
Demonstrates how to import and use the useI18n hook within a script setup block to access translation functions.
```vue
{{ t("message.hello") }}
```
--------------------------------
### Run Nuxt 3 Development Server
Source: https://vue-i18n.intlify.dev/guide/integrations/nuxt3
Commands to start the Nuxt 3 development server.
```npm
npm run dev
```
```yarn
yarn dev
```
```pnpm
pnpm dev
```
--------------------------------
### Vue 2.6 Composition API Setup with vue-i18n-bridge
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
Illustrates setting up vue-i18n with Composition API in a Vue 2.6 application using `vue-i18n-bridge`. This example includes the necessary `@vue/composition-api` plugin and demonstrates the usage of `createI18n` and `useI18n`.
```js
import Vue from 'vue'
import VueCompositionAPI, { createApp } from '@vue/composition-api'
import { createI18n, useI18n } from 'vue-i18n-bridge'
Vue.use(VueCompositionAPI)
Vue.use(VueI18n, { bridge: true }) // you must specify '{ bridge: true }' plugin option when install vue-i18n
// `createI18n` options is almost same vue-i18n (vue-i18n@v9.x) API
const i18n = createI18n({
legacy: false,
locale: 'ja',
messages: {
en: {
message: {
hello: 'hello, {name}!'
}
},
ja: {
message: {
hello: 'こんにちは、{name}!'
}
}
}
}, VueI18n) // `createI18n` which is provide `vue-i18n-bridge` has second argument, you **must** pass `VueI18n` constructor which is provide `vue-i18n`
const app = createApp({
setup() {
// `useI18n` options is almost same vue-i18n (vue-i18n@v9.x) API
const { t, locale } = useI18n()
// ... todo something
return { t, locale }
}
})
app.use(i18n) // you must install `i18n` instance which is created by `createI18n`
app.mount('#app')
```
--------------------------------
### ES Modules Import via CDN
Source: https://vue-i18n.intlify.dev/guide/installation
Import Vue I18n as ES Modules using CDN links from unpkg.com. This is ideal for modern JavaScript projects using module bundlers or native ES module support.
```html
Car:
{{ t('car', 1) }}
{{ t('car', 2) }}
Apple:
{{ t('apple', 0) }}
{{ t('apple', 1) }}
{{ t('apple', { count: 10 }, 10) }}
{{ t('apple', 10) }}
Banana:
{{ t('banana', { n: 1 }, 1) }}
{{ t('banana', 1) }}
{{ t('banana', { n: 'too many' }, 100) }}
```
--------------------------------
### I18n Instance
Source: https://vue-i18n.intlify.dev/api/general
The main I18n instance used for installation as a Vue plugin.
```APIDOC
## I18n
### Description
The instance required for installation as the Vue plugin.
### Properties
- **global** (readonly VueI18n or Composer) - The property accessible to the global Composer instance or VueI18n instance. If `I18n#mode` is 'legacy', it's a `VueI18n` instance; otherwise, it's a `Composer` instance.
- **mode** (readonly I18nMode) - Vue I18n API mode. DEPRECATED: will be removed at vue-i18n v12. Default value: 'legacy'.
### Methods
- **dispose()**: Release global scope resource.
- **install(app: App, ...options: unknown[])**: Install entry point. Installs Vue I18n into a target Vue application.
- **Parameters**:
- **app** (App) - A target Vue app instance
- **options** (unknown[]) - An install options
```
--------------------------------
### TypeScript Setup with vue-i18n-bridge (TypeScript)
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
This TypeScript example shows how to configure vue-i18n-bridge for Vue 2.x legacy API. It utilizes `castToVueI18n` to ensure proper type inference for the i18n instance, which is crucial for TypeScript projects.
```typescript
import Vue from 'vue'
import VueCompositionAPI from '@vue/composition-api'
import { createI18n, useI18n, castToVueI18n } from 'vue-i18n-bridge'
Vue.use(VueCompositionAPI)
Vue.use(VueI18n, { bridge: true })
// you need to cast `i18n` instance
const i18n = castToVueI18n(createI18n({
locale: 'ja',
messages: {
en: {
message: {
hello: 'hello, {name}!'
}
},
ja: {
message: {
hello: 'こんにちは、{name}!'
}
}
}
}, VueI18n))
Vue.use(i18n)
const app = new Vue({ i18n })
app.$mount('#app')
```
--------------------------------
### Importing Vue I18n with a Bundler
Source: https://vue-i18n.intlify.dev/guide/extra/dist
Demonstrates how to explicitly import the full build of Vue I18n when using a bundler, which includes the runtime compiler for in-browser message compilation.
```javascript
import { createI18n } from "vue-i18n/dist/vue-i18n.esm-bundler.js";
```
--------------------------------
### Vue I18n Translation Example (HTML)
Source: https://vue-i18n.intlify.dev/api/general
An example demonstrating how to use the $t function in Vue.js templates to display a translated greeting with dynamic values. This showcases the integration of i18n within Vue components.
```html
{{ $t('greeting', { name: 'DIO' }) }}
```
--------------------------------
### Configure Quasar CLI for I18n
Source: https://vue-i18n.intlify.dev/guide/advanced/sfc
Modifies the Quasar build configuration to support i18n resource loading and custom block processing via webpack chains.
```javascript
build: {
chainWebpack: chain => {
chain.module
.rule('i18n-resource')
.test(/\.(json5?|ya?ml)$/)
.include.add(path.resolve(__dirname, './src/i18n'))
.end()
.type('javascript/auto')
.use('i18n-resource')
.loader('@intlify/vue-i18n-loader')
chain.module
.rule('i18n')
.resourceQuery(/blockType=i18n/)
.type('javascript/auto')
.use('i18n')
.loader('@intlify/vue-i18n-loader')
}
}
```
--------------------------------
### Define Plugin and Scope Types
Source: https://vue-i18n.intlify.dev/api/general
Core type definitions for Vue I18n plugin installation options, scope settings, and versioning.
```typescript
export interface I18nPluginOptions {
globalInstall?: boolean;
}
export type I18nScope = 'local' | 'parent' | 'global';
VERSION: string;
```
--------------------------------
### Install vue-i18n-bridge via yarn
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
Installs the `vue-i18n-bridge` package using yarn. This command is an alternative to npm for managing project dependencies.
```sh
yarn add vue-i18n-bridge
```
--------------------------------
### Use useI18n in Vue Components
Source: https://vue-i18n.intlify.dev/guide/migration/vue3
Demonstrates how to access translation functions using the 'useI18n' hook within both standard 'setup' options and '
{{ $t('hello') }}
{{ t('hello') }}
```
```vue
{{ $t('hello') }}
{{ t('hello') }}
```
--------------------------------
### Configure Vue I18n for Composition API
Source: https://vue-i18n.intlify.dev/guide/advanced/composition
To enable the Composition API, the legacy option must be set to false during the initialization of the i18n instance.
```javascript
const i18n = VueI18n.createI18n({
legacy: false,
locale: 'ja',
fallbackLocale: 'en',
messages: {
en: { message: { hello: 'hello world' } },
ja: { message: { hello: 'こんにちは、世界' } }
}
})
```
--------------------------------
### Render HTML messages with v-html
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
Illustrates how to include HTML tags in translation strings and render them using the v-html directive, noting associated XSS risks.
```javascript
const messages = {
en: {
message: {
hello: 'hello world'
}
}
}
```
```html
```
--------------------------------
### Apply pluralization in component interpolation
Source: https://vue-i18n.intlify.dev/guide/advanced/component
Illustrates how to combine the plural prop with component interpolation to handle dynamic pluralized messages within templates.
```html
{{ count }}
```
```javascript
const i18n = createI18n({
messages: {
en: { message: { plural: 'no bananas | {n} banana | {n} bananas' } }
}
})
```
--------------------------------
### Named Interpolation Example in Vue I18n
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
Demonstrates named interpolation using JavaScript variables within Vue I18n templates. It shows how to define locale messages with placeholders and pass JavaScript object properties to the $t function for dynamic content. The variable names in placeholders must start with a letter or underscore.
```javascript
const messages = {
en: {
message: {
hello: '{msg} world'
}
}
}
```
```html
{{ $t('message.hello', { msg: 'hello' }) }}
```
```html
hello world
```
--------------------------------
### List Interpolation Example in Vue I18n
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
Illustrates list interpolation in Vue I18n, where array elements are used to fill placeholders in locale messages. This method is useful for ordered dynamic content. The example shows defining a message with a numeric placeholder and passing an array to the $t function.
```javascript
const messages = {
en: {
message: {
hello: '{0} world'
}
}
}
```
```html
{{ $t('message.hello', ['hello']) }}
```
```html
hello world
```
--------------------------------
### Initialize useI18n correctly in Vue components
Source: https://vue-i18n.intlify.dev/guide/advanced/composition
Demonstrates the correct pattern of calling useI18n once per component to avoid duplicate scope warnings. It shows how to destructure all required translation and locale properties from a single instance.
```javascript
export default {
setup() {
const { t, locale, tm, d, n } = useI18n({
locale: 'en',
messages: {
en: { hello: 'Hello', world: 'World' },
ja: { hello: 'こんにちは', world: '世界' }
}
})
return { t, locale }
}
}
```
--------------------------------
### Literal Interpolation Example in Vue I18n
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
Shows how to use literal interpolation in Vue I18n for embedding special characters like '@' directly into messages. This is achieved by quoting the literal string within the message. The example demonstrates interpolating account and domain parts to form an email address.
```javascript
const messages = {
en: {
address: "{account}{'@'}{domain}"
}
}
```
```html
```
--------------------------------
### Linked Messages Example in Vue I18n
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
Demonstrates the use of linked messages in Vue I18n, allowing one locale message to reference another. This is done using the '@:key' syntax, which helps in reusing text and maintaining consistency across translations. The example shows linking to 'message.dio' and 'message.the_world'.
```javascript
const messages = {
en: {
message: {
the_world: 'the world',
dio: 'DIO:',
linked: '@:message.dio @:message.the_world !!!!'
}
}
}
```
```html
{{ $t('message.linked') }}
```
```html
DIO: the world !!!!
```
--------------------------------
### Initialize Nuxt 3 Application
Source: https://vue-i18n.intlify.dev/guide/integrations/nuxt3
Commands to scaffold a new Nuxt 3 project using various package managers.
```npx
npx nuxi init nuxt3-app-vue-i18n
```
```pnpm
pnpm dlx nuxi init nuxt3-app-vue-i18n
```
--------------------------------
### Named Interpolation with Modifier in Vue Template (HTML)
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
Shows a Vue.js template example using the $t function with named interpolation and a modifier (@.lower) to format a linked locale message.
```html
```
--------------------------------
### Initialize petite-vue-i18n with Vue.js (CDN)
Source: https://vue-i18n.intlify.dev/guide/advanced/lite
Demonstrates how to set up and use petite-vue-i18n in a Vue.js application via CDN. It includes creating the Vue app instance and integrating the i18n instance using the Composition API.
```html
```
--------------------------------
### Literal Interpolation with Modifier in Vue Template (HTML)
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
Presents a Vue template example utilizing the $t function with literal interpolation and a modifier (@.lower) to format a specific part of a locale message.
```html
{{ $t('literalMessage') }}
```
--------------------------------
### Combined Modifiers and Interpolations (JavaScript)
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
Provides a JavaScript example of locale messages demonstrating the combined use of built-in modifiers (@.lower, @.upper, @.capitalize) with named, list, and literal interpolations.
```javascript
const messages = {
en: {
message: {
greeting: "Hello, @.lower:{'message.name'}! You have {count} new messages.",
name:"{name}"
},
welcome: "Welcome, @.upper:{'name'}! Today is @.capitalize:{'day'}.",
name: '{0}',
day: '{1}',
literalMessage: "This is an email: foo{'@'}@.lower:domain",
domain: 'SHOUTING'
}
}
```
--------------------------------
### Create and Provide i18n Instance for Web Components (Vue)
Source: https://vue-i18n.intlify.dev/guide/advanced/wc
This Vue SFC prepares an i18n instance using `createI18n` and provides it to child Web Components via `I18nInjectionKey`. It's designed to be used as a host for other i18n-enabled Web Components. It requires Vue I18n and Vue.
```vue
```
--------------------------------
### Translate with Key and List (Vue Template)
Source: https://vue-i18n.intlify.dev/guide/migration/breaking10
Demonstrates translating a key with a list of values using `$tc` in v9.x and the `$t` function with a list and pluralization in v10 and later.
```vue
{{ $tc('banana', ['dio']) }}
```
```vue
{{ $t('banana', ['dio'], 1) }}
```
--------------------------------
### Basic Translation Usage with petite-vue-i18n
Source: https://vue-i18n.intlify.dev/guide/advanced/lite
Illustrates a 'Hello world' example using petite-vue-i18n's Composition API for basic translations. It shows how to define messages and use the `t` function in both the template and script.
```html
{{ t('hello world') }}
```
```javascript
const { createApp } = Vue
const { createI18n, useI18n } = PetiteVueI18n
// or for ES modules
// import { createApp } from 'vue'
// import { createI18n } from 'petite-vue-i18n'
const i18n = createI18n({
locale: 'en',
messages: {
en: {
'hello world': 'Hello world!'
},
ja: {
'hello world': 'こんにちは、世界!'
}
}
})
// define App component
const App = {
setup() {
const { t } = useI18n()
return { t }
}
}
const app = createApp(App)
app.use(i18n)
app.mount('#app')
```
--------------------------------
### UMD Module Usage for Vue 2.6 in Browser (JavaScript)
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
This example shows how to integrate vue-i18n-bridge using UMD modules in a browser for Vue 2.6. It imports `createApp` from `VueCompositionAPI` and `createI18n` from `VueI18nBridge`, followed by the standard i18n setup and application mounting.
```javascript
const { createApp } = VueCompositionAPI // exported UMD which is named by `VueCompositionAPI`
const { createI18n, useI18n } = VueI18nBridge // exported UMD which is named by `VueI18nBridge`
Vue.use(VueCompositionAPI)
Vue.use(VueI18n, { bridge: true })
const i18n = createI18n({
locale: 'ja',
messages: {
// ...
}
}, VueI18n)
const app = createApp({}, {
// ...
})
app.use(i18n)
app.mount('#app') // Vue app host container element
```
--------------------------------
### Vue 2.7 Setup with vue-i18n-bridge (JavaScript)
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
This snippet demonstrates how to set up vue-i18n-bridge for Vue 2.7 using the legacy API. It involves importing necessary modules, configuring VueI18n with bridge mode, creating an i18n instance with messages, and installing it into the Vue application.
```javascript
import Vue from 'vue'
import { createI18n, useI18n } from 'vue-i18n-bridge'
Vue.use(VueI18n, { bridge: true }) // you must specify '{ bridge: true }' plugin option when install vue-i18n
// `createI18n` options is almost same vue-i18n (vue-i18n@v9.x) API
const i18n = createI18n({
locale: 'ja',
messages: {
en: {
message: {
hello: 'hello, {name}!'
}
},
ja: {
message: {
hello: 'こんにちは、{name}!'
}
}
}
}, VueI18n) // `createI18n` which is provide `vue-i18n-bridge` has second argument, you **must** pass `VueI18n` constructor which is provide `vue-i18n`
Vue.use(i18n) // you must install `i18n` instance which is created by `createI18n`
const app = new Vue({ i18n })
app.$mount('#app')
```
--------------------------------
### Translate with Key, Choice, and Locale (Vue Template)
Source: https://vue-i18n.intlify.dev/guide/migration/breaking10
Demonstrates translating a key with a choice and a specific locale using `$tc` in v9.x and the `$t` function with pluralization and options in v10 and later.
```vue
{{ $tc('banana', 2, 'ja') }}
```
```vue
{{ $t('banana', 2, { locale: 'ja' }) }}
```
--------------------------------
### Translate with Key, Choice, and List (Vue Template)
Source: https://vue-i18n.intlify.dev/guide/migration/breaking10
Shows how to translate a key with a choice and a list of values using `$tc` in v9.x and the `$t` function with a list and pluralization in v10 and later.
```vue
{{ $tc('banana', 2, ['dio']) }}
```
```vue
{{ $t('banana', ['dio'], 2) }}
```
--------------------------------
### Translate with Key and Choice (Vue Template)
Source: https://vue-i18n.intlify.dev/guide/migration/breaking10
Illustrates translating a key with a choice for pluralization using `$tc` in v9.x and the `$t` function with pluralization in v10 and later.
```vue
{{ $tc('banana', 2) }}
```
```vue
{{ $t('banana', 2) }}
```
--------------------------------
### ICU Message Format Compiler Implementation (TypeScript)
Source: https://vue-i18n.intlify.dev/guide/advanced/format
An example implementation of a message compiler using 'intl-messageformat' to support the ICU Message Format. It handles string messages by creating an IntlMessageFormat instance and returns a function to format messages with provided values. It includes basic error handling for non-string messages.
```typescript
import IntlMessageFormat from 'intl-messageformat'
import type { MessageCompiler, CompileError, MessageContext } from 'vue-i18n'
export const messageCompiler: MessageCompiler = (
message,
{ locale, key, onError }
) => {
if (typeof message === 'string') {
/**
* You can tune your message compiler performance more with your cache strategy or also memoization at here
*/
const formatter = new IntlMessageFormat(message, locale)
return (ctx: MessageContext) => {
return formatter.format(ctx.values)
}
} else {
/**
* for AST.
* If you would like to support it,
* You need to transform locale messages such as `json`, `yaml`, etc. with the bundle plugin.
*/
onError && onError(new Error('not support for AST') as CompileError)
return () => key
}
}
```
--------------------------------
### Vue-i18n HTML Escaping Example (JavaScript)
Source: https://vue-i18n.intlify.dev/guide/essentials/syntax
This snippet illustrates the security implications of interpolating potentially harmful HTML strings in Vue-i18n translations. It shows how to use the `escapeParameter: true` option to safely render HTML content, preventing Cross-Site Scripting (XSS) attacks. Without escaping, user input is directly rendered, while with escaping, HTML tags are converted to their entity equivalents.
```javascript
const userInput = ''
// Without escape parameter (DANGEROUS):
$t('message.welcome', { name: userInput })
// Result: Welcome !
// With escape parameter (SAFE):
$t('message.welcome', { name: userInput }, { escapeParameter: true })
// Result: Welcome <img src=x onerror=alert(1)>!
```
--------------------------------
### Vue 2.6 Setup with vue-i18n-bridge (JavaScript)
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
This code illustrates the setup for vue-i18n-bridge in Vue 2.6 using the legacy API. It requires importing VueCompositionAPI alongside vue-i18n-bridge, enabling bridge mode, and then initializing the i18n instance similar to the Vue 2.7 setup.
```javascript
import Vue from 'vue'
import VueCompositionAPI from '@vue/composition-api'
import { createI18n, useI18n } from 'vue-i18n-bridge'
Vue.use(VueCompositionAPI)
Vue.use(VueI18n, { bridge: true }) // you must specify '{ bridge: true }' plugin option when install vue-i18n
// `createI18n` options is almost same vue-i18n (vue-i18n@v9.x) API
const i18n = createI18n({
locale: 'ja',
messages: {
en: {
message: {
hello: 'hello, {name}!'
}
},
ja: {
message: {
hello: 'こんにちは、{name}!'
}
}
}
}, VueI18n) // `createI18n` which is provide `vue-i18n-bridge` has second argument, you **must** pass `VueI18n` constructor which is provide `vue-i18n`
Vue.use(i18n) // you must install `i18n` instance which is created by `createI18n`
const app = new Vue({ i18n })
app.$mount('#app')
```
--------------------------------
### Vue 2.7 Composition API Setup with vue-i18n-bridge
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
Demonstrates setting up vue-i18n with Composition API in a Vue 2.7 application using `vue-i18n-bridge`. It shows how to import necessary modules, create the i18n instance, and use `useI18n` for translation and locale management.
```js
import Vue from 'vue'
import { createApp } from 'vue-demi'
import { createI18n, useI18n } from 'vue-i18n-bridge'
Vue.use(VueI18n, { bridge: true }) // you must specify '{ bridge: true }' plugin option when install vue-i18n
// `createI18n` options is almost same vue-i18n (vue-i18n@v9.x) API
const i18n = createI18n({
legacy: false,
locale: 'ja',
messages: {
en: {
message: {
hello: 'hello, {name}!'
}
},
ja: {
message: {
hello: 'こんにちは、{name}!'
}
}
}
}, VueI18n) // `createI18n` which is provide `vue-i18n-bridge` has second argument, you **must** pass `VueI18n` constructor which is provide `vue-i18n`
const app = createApp({
setup() {
// `useI18n` options is almost same vue-i18n (vue-i18n@v9.x) API
const { t, locale } = useI18n()
// ... todo something
return { t, locale }
}
})
app.use(i18n) // you must install `i18n` instance which is created by `createI18n`
app.mount('#app')
```
--------------------------------
### Install vue-i18n-bridge via pnpm
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
Installs the `vue-i18n-bridge` package using pnpm. This is another package manager option for adding the bridge to your project.
```sh
pnpm add vue-i18n-bridge
```
--------------------------------
### Install vue-i18n-bridge via npm
Source: https://vue-i18n.intlify.dev/guide/migration/vue2
Installs the `vue-i18n-bridge` package using npm. This is a prerequisite for using the bridge functionality in Vue 2 applications.
```sh
npm install vue-i18n-bridge
```
--------------------------------
### Translate with Key and Locale (Vue Template)
Source: https://vue-i18n.intlify.dev/guide/migration/breaking10
Illustrates translating a key with a specified locale using `$tc` in v9.x and the updated `$t` function with options in v10 and later.
```vue
{{ $tc('banana', 'ja') }}
```
```vue
{{ $t('banana', 1, { locale: 'ja' }) }}
```
--------------------------------
### Create Locale Resource Files
Source: https://vue-i18n.intlify.dev/guide/integrations/nuxt3
This command creates a 'locales' directory and then creates JSON files for English, French, and Japanese locale resources. These files will store the translated strings for the application.
```shell
mkdir locales
touch locales/en.json # for english
touch locales/fr.json # for french
touch locales/ja.json # for japanese
```
--------------------------------
### Translate with Key, Choice, and Named Values (Vue Template)
Source: https://vue-i18n.intlify.dev/guide/migration/breaking10
Illustrates translating a key with a choice and named interpolation values using `$tc` in v9.x and the `$t` function with named values and pluralization in v10 and later.
```vue
{{ $tc('banana', 2, { name: 'dio' }) }}
```
```vue
{{ $t('banana', { name: 'dio' }, 2) }}
```
--------------------------------
### I18n Instance Interface
Source: https://vue-i18n.intlify.dev/api/general
The primary interface for the I18n instance required for Vue plugin installation. It manages the global scope and provides methods for installation and resource disposal.
```typescript
export interface I18n = {}, DateTimeFormats extends Record = {}, NumberFormats extends Record = {}, OptionLocale = Locale, Legacy = boolean> {
readonly global: Legacy extends true ? VueI18n : Legacy extends false ? Composer : unknown;
readonly mode: I18nMode;
dispose(): void;
install(app: App, ...options: unknown[]): void;
}
```
--------------------------------
### Number Formatting (with Key, Options, and Locale)
Source: https://vue-i18n.intlify.dev/api/composition
Formats a number using a specific number format key or options, and a target locale. This provides explicit control over the formatting locale.
```APIDOC
## POST /format/number/key-options-locale
### Description
Formats a number using a specified key for number formats or additional options, and a target locale. This enables formatting for a specific locale, overriding global or local scope settings.
### Method
POST
### Endpoint
/format/number/key-options-locale
### Parameters
#### Request Body
- **value** (number) - Required - The number to format.
- **keyOrOptions** (string | object) - Required - A key referencing a registered number format, or an object containing number formatting options.
- **locale** (string) - Required - The target locale for formatting (e.g., 'en-US', 'fr-FR').
### Request Example
```json
{
"value": 12345.67,
"keyOrOptions": "currency",
"locale": "fr-FR"
}
```
### Response
#### Success Response (200)
- **formattedValue** (string) - The number formatted according to the specified key, options, and locale.
#### Response Example
```json
{
"formattedValue": "12 345,67 $"
}
```
```
--------------------------------
### Vue.js Setup with Vue-i18n (Object Syntax)
Source: https://vue-i18n.intlify.dev/guide/advanced/directive
Configures a Vue application with vue-i18n, including more complex message structures for named parameters and pluralization. This setup is necessary for using the v-t directive with object syntax.
```javascript
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
locale: 'ja',
messages: {
en: {
message: {
hi: 'Hi, {name}!',
bye: 'good bye!',
apple: 'no apples | one apple | {count} apples'
}
},
ja: {
message: {
hi: 'こんにちは、 {name}!',
bye: 'さようなら!',
apple: 'リンゴはありません | 一つのりんご | {count} りんご'
}
}
}
})
const app = createApp({
data() {
return {
byePath: 'message.bye',
appleCount: 7,
}
}
})
app.use(i18n)
app.mount('#object-syntax')
```
--------------------------------
### Initialize petite-vue-i18n with Vue.js (Package Manager)
Source: https://vue-i18n.intlify.dev/guide/advanced/lite
Shows how to initialize petite-vue-i18n within a Vue.js project when using package managers like npm or yarn. This setup involves importing necessary functions and configuring the i18n instance.
```javascript
import { createApp } from 'vue'
import { createI18n } from 'petite-vue-i18n'
const i18n = createI18n({
// something vue-i18n options here ...
})
const app = createApp({
// something vue options here ...
})
app.use(i18n)
app.mount('#app')
```
--------------------------------
### Register Custom Elements and Mount Vue App (JavaScript)
Source: https://vue-i18n.intlify.dev/guide/advanced/wc
This JavaScript code registers the defined custom elements ('i18n-host', 'hello-i18n') with the browser and then mounts the main Vue application. It requires Vue and the exported custom element classes.
```javascript
import { createApp } from 'vue'
import { I18nHostElement } from './path/to/I18nHostElement'
import { HelloI18nElement } from './path/to/HelloI18nElement'
import App from './App.vue'
customElements.define('i18n-host', I18nHostElement)
customElements.define('hello-i18n', HelloI18nElement)
createApp(App).mount('#app')
```
--------------------------------
### Number Formatting (Basic)
Source: https://vue-i18n.intlify.dev/api/composition
Formats a given number using the current locale's number formatting rules. If used reactively, it updates when the locale changes.
```APIDOC
## POST /format/number
### Description
Formats a number using the current locale's default number formatting rules. This function is reactive and will update when the locale changes.
### Method
POST
### Endpoint
/format/number
### Parameters
#### Request Body
- **value** (number) - Required - The number to format.
### Request Example
```json
{
"value": 12345.67
}
```
### Response
#### Success Response (200)
- **formattedValue** (string) - The number formatted according to the current locale.
#### Response Example
```json
{
"formattedValue": "12,345.67"
}
```
```
--------------------------------
### Install Vue I18n Dependency
Source: https://vue-i18n.intlify.dev/guide/integrations/nuxt3
Commands to add the vue-i18n package as a development dependency.
```npm
npm install vue-i18n -D
```
```yarn
yarn add vue-i18n -D
```
```pnpm
pnpm add -D vue-i18n
```
--------------------------------
### Use Translation API for Pluralization
Source: https://vue-i18n.intlify.dev/guide/essentials/pluralization
Use the $t function to select pluralized strings by passing the message key and a numeric value or object.
```html