Skip to content

useLocale — i18n ​

17:43

Description ​

useLocale provides a translation function and locale management: t resolves a message by key path and replaces {key} placeholders, setLocale switches the language and persists it, and currentLocale / locales expose the active locale and locale list reactively.

Examples ​

Current language info ​

Reads label, name and locale from currentLocale, falling back to - when no locale matches.

View source
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item title="当前语言" :value="currentLangText" :arrow="false" />
        <ux-cell-item title="Locale" :value="currentLocaleText" :arrow="false" :border-bottom="false" />
    </ux-cell-group>
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

const { currentLocale } = useLocale();

// currentLocale 可能为 null,统一在计算属性里收敛
const currentLangText = computed((): string => {
    const cur = currentLocale.value;
    if (cur == null) return '-';
    return cur.label + ' (' + cur.name + ')';
});

const currentLocaleText = computed((): string => {
    const cur = currentLocale.value;
    return cur == null ? '-' : cur.locale;
});
</script>

Language switching ​

Buttons call setLocale to switch between zh-CN, en-US and fr-FR, and the active language is highlighted with the primary theme.

View source
vue
<template>
    <ux-button size="small" :type="isActive('zh-CN') ? 'primary' : 'info'" block text="简体中文" @click="switchLocale('zh-CN')" />
    <ux-gap :height="8" />
    <ux-button size="small" :type="isActive('en-US') ? 'primary' : 'info'" block text="English" @click="switchLocale('en-US')" />
    <ux-gap :height="8" />
    <ux-button size="small" :type="isActive('fr-FR') ? 'primary' : 'info'" block text="Français" @click="switchLocale('fr-FR')" />
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

const { currentLocale, setLocale } = useLocale();

const currentName = computed((): string => {
    const cur = currentLocale.value;
    return cur == null ? '' : cur.name;
});

function isActive(name: string): boolean {
    return currentName.value == name;
}

// 切换语言,内部会持久化到本地存储
function switchLocale(name: string): void {
    setLocale(name);
}
</script>

Translation examples ​

t resolves built-in component messages by keys such as uModal.title and uSearch.placeholder, which refresh after a language switch.

View source
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item
            v-for="(item, index) in translateRows"
            :key="index"
            :title="item.title"
            :value="item.value"
            :arrow="false"
            :border-bottom="!item.last"
        />
    </ux-cell-group>
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

const { t } = useLocale();

type CellRow = {
    title: string;
    value: string;
    last: boolean;
};

// 语言切换后这些文案会随当前语言变化
const translateRows = computed((): CellRow[] => [
    { title: '弹窗标题', value: t('uModal.title'), last: false },
    { title: '确认按钮', value: t('uModal.confirmText'), last: false },
    { title: '搜索占位符', value: t('uSearch.placeholder'), last: false },
    { title: '上传文案', value: t('uUpload.uploadText'), last: true }
]);
</script>

Placeholder substitution example ​

The second argument of t is a replacement object, so the {ext} placeholder in uUpload.notAllowedExt is replaced with pdf.

View source
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item title="原文(含占位符)" value="uUpload.notAllowedExt" :arrow="false" />
        <ux-cell-item title="替换后" :value="placeholderReplaced" :arrow="false" :border-bottom="false" />
    </ux-cell-group>
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

const { t } = useLocale();

// 第二个参数为替换对象,字符串中的 {ext} 会被替换
const placeholderReplaced = computed((): string => t('uUpload.notAllowedExt', { ext: 'pdf' }));
</script>

Namespace example (uUpload) ​

useLocale('uUpload') binds the namespace up front, so t keys no longer need the uUpload. prefix.

View source
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item
            v-for="(item, index) in namespaceRows"
            :key="index"
            :title="item.title"
            :value="item.value"
            :arrow="false"
            :border-bottom="!item.last"
        />
    </ux-cell-group>
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

// 指定命名空间后,t 的 key 不必再带前缀
const { t: uploadT } = useLocale('uUpload');

type CellRow = {
    title: string;
    value: string;
    last: boolean;
};

const namespaceRows = computed((): CellRow[] => [
    { title: 'uploadText', value: uploadT('uploadText'), last: false },
    { title: 'uploadImage', value: uploadT('uploadImage'), last: false },
    { title: 'retry', value: uploadT('retry'), last: true }
]);
</script>

Available languages ​

Reads locales to list the registered languages with their label and name, with the index generated in the data layer.

View source
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item
            v-for="(item, index) in localeRows"
            :key="index"
            :title="item.title"
            :value="item.value"
            :arrow="false"
            :border-bottom="!item.last"
        />
    </ux-cell-group>
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

const { currentLocale, locales } = useLocale();

type CellRow = {
    title: string;
    value: string;
    last: boolean;
};

// last 在数据层生成,模板不需要读源数组长度
const localeRows = computed((): CellRow[] => {
    const list = locales.value;
    const rows: CellRow[] = [];
    for (let i = 0; i < list.length; i++) {
        rows.push({
            title: (i + 1).toString(),
            value: list[i].label + ' (' + list[i].name + ')',
            last: i == list.length - 1
        });
    }
    return rows;
});
</script>

Language pack merge demo ​

The third argument of t selects a locale, so en-US and fr-FR messages are read regardless of the active language.

View source
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item
            v-for="(item, index) in mergeRows"
            :key="index"
            :title="item.title"
            :value="item.value"
            :arrow="false"
            :border-bottom="!item.last"
        />
    </ux-cell-group>
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

const { t } = useLocale();

type CellRow = {
    title: string;
    value: string;
    last: boolean;
};

// 第三个参数指定语言,结果不受当前语言影响
const mergeRows: CellRow[] = [
    { title: 'en-US 分区副标题', value: t('uSection.subTitle', null, 'en-US'), last: false },
    { title: 'en-US 空状态', value: t('uEmpty.data', null, 'en-US'), last: false },
    { title: 'en-US 弹窗标题', value: t('uModal.title', null, 'en-US'), last: false },
    { title: 'fr-FR 空搜索', value: t('uEmpty.search', null, 'fr-FR'), last: false },
    { title: 'fr-FR 分区副标题', value: t('uSection.subTitle', null, 'fr-FR'), last: true }
];
</script>

uCalendar component translation ​

Reads uCalendar weekday abbreviations and year/month units from the built-in packs, plus the uEmpty cart and search empty texts.

View source
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item
            v-for="(item, index) in builtinRows"
            :key="index"
            :title="item.title"
            :value="item.value"
            :arrow="false"
            :border-bottom="!item.last"
        />
    </ux-cell-group>
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

const { t } = useLocale();

type CellRow = {
    title: string;
    value: string;
    last: boolean;
};

// 内置语言包覆盖日历、空状态、上传等组件文案
const builtinRows: CellRow[] = [
    {
        title: '星期缩写',
        value: t('uCalendar.sun') + ' ' + t('uCalendar.mon') + ' ' + t('uCalendar.tue') + ' ' + t('uCalendar.wed'),
        last: false
    },
    { title: '年月单位', value: t('uCalendar.year') + ' ' + t('uCalendar.month'), last: false },
    { title: '购物车空', value: t('uEmpty.car'), last: false },
    { title: '搜索空', value: t('uEmpty.search'), last: true }
];
</script>

uEmpty component translation ​

Uses the same built-in pack lookup to show the uEmpty.car and uEmpty.search empty-state texts.

View source
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item
            v-for="(item, index) in builtinRows"
            :key="index"
            :title="item.title"
            :value="item.value"
            :arrow="false"
            :border-bottom="!item.last"
        />
    </ux-cell-group>
</template>

<script setup lang="ts">
import { useLocale } from '@/uni_modules/uview-pro-x';

const { t } = useLocale();

type CellRow = {
    title: string;
    value: string;
    last: boolean;
};

// 内置语言包覆盖日历、空状态、上传等组件文案
const builtinRows: CellRow[] = [
    {
        title: '星期缩写',
        value: t('uCalendar.sun') + ' ' + t('uCalendar.mon') + ' ' + t('uCalendar.tue') + ' ' + t('uCalendar.wed'),
        last: false
    },
    { title: '年月单位', value: t('uCalendar.year') + ' ' + t('uCalendar.month'), last: false },
    { title: '购物车空', value: t('uEmpty.car'), last: false },
    { title: '搜索空', value: t('uEmpty.search'), last: true }
];
</script>

API ​

Parameters ​

ParameterDescriptionTypeDefaultVersion
namespaceNamespace prefix; when set, t keys are automatically prefixed as namespace.keystring''-

Returns ​

FieldDescriptionType
currentLocaleActive locale info (name / label / locale), null when unmatchedRef<Locale | null>
localesRegistered locale listRef<Locale[]>
tTranslation function; returns the key itself when it is missing and accepts an optional locale as the third argument(key: string, replacements?: JsonObject | null, localeName?: string) => string
setLocaleSwitches the active locale and persists it; warns without switching when the locale is not registered(name: string) => void
getLocalesReturns the registered locale list() => Locale[]
getCurrentLocaleReturns the active locale info() => Locale | null
initLocaleInitializes locale packs (called internally by install)(locale?: UViewProXLocaleOptions | null) => void

Notes ​

  • Only on H5 (inside the WEB conditional compilation) does it read the lang= parameter from location.href and inject the locale; on other platforms this step always returns null and does not affect normal locale resolution.
  • Locale resolution priority: URL injection > defaultLocale when isForce is true > the language saved in local storage > defaultLocale (built-in default zh-CN).
  • setLocale only accepts registered locales; an unknown name just logs a warning and does not switch, while a successful switch writes to local storage under uview-pro-x-locale.
  • t returns the key as-is when it cannot be found instead of throwing an error.