Skip to content

Vue RTL: adding right-to-left support to Vue apps

Add RTL support to Vue with locale-driven document attributes, logical component styles, Teleport direction and bidi-safe template values.

By , Founder of Ritla

Guide13 min read

A Vue component can display Arabic translations while its service queue still begins on the left. A note can inherit RTL inside the page, then lose that direction when Teleport places it under the document body. These are different failures: translated messages, component ancestry and browser direction do not share one automatic setting.

Vue renders the attributes and styles you give it. Adding Arabic support means connecting those attributes to the application's locale, making component CSS direction-aware and controlling boundaries around mixed-content values. An i18n plugin translates messages; it does not complete that work by itself.

This guide follows an observatory's equipment-service queue. The examples use Vue 3 Composition API, Vue I18n's Composition API mode and, for the custom input example, Vue 3.4 or later. Each example isolates one boundary rather than assuming a component library can fix the entire document.

Make the document follow the resolved application locale#

Start with a language decision that the application owns. For this example, the supported locales are exactly en and ar. Real applications should resolve route, account or saved preferences into their supported locale set before committing the change.

On an Arabic response, the document should already declare:

html
<html lang="ar" dir="rtl">

The W3C direction guidance explains why direction belongs in HTML. Language identifies the text's language; it does not set RTL layout. R001 covers document direction missing, contradicted, or declared only in CSS.

For a browser-rendered Vue application, synchronize the root attributes before mounting and whenever the global locale changes. This is a client entry, not code to run unchanged on the server:

ts
// src/main.ts: App.vue is the application's existing root component.import { createApp, watch } from 'vue';import { createI18n } from 'vue-i18n';import App from './App.vue'; const localeMeta: Record<string, { lang: string; dir: 'ltr' | 'rtl' }> = {  en: { lang: 'en', dir: 'ltr' },  ar: { lang: 'ar', dir: 'rtl' },};const i18n = createI18n({  legacy: false,  locale: 'ar',  fallbackLocale: 'en',  messages: {    en: {      queueTitle: 'Observatory equipment service',      serviceRecord: 'Equipment service record: {reference}',    },    ar: {      queueTitle: 'صيانة أجهزة المرصد',      serviceRecord: 'ملف صيانة الجهاز: {reference}',    },  },}); watch(i18n.global.locale, (activeLocale) => {  const meta = localeMeta[activeLocale];  if (!meta) throw new Error('Resolve a supported locale before applying it.');  document.documentElement.lang = meta.lang;  document.documentElement.dir = meta.dir;}, { immediate: true, flush: 'sync' }); createApp(App).use(i18n).mount('#app');

The eager watcher applies the initial attributes before mount. Its synchronous callback updates these small document attributes when the locale ref changes. Vue's watcher documentation describes eager callbacks and flush timing; synchronous watchers should not become a place for expensive rendering work.

The example deliberately starts in Arabic. Replace that initial choice with the application's resolved locale, and keep the initial document consistent with it. A static English shell can otherwise appear before the client changes direction. A watcher cannot rewrite HTML that the browser has already received.

Keep this responsibility in one application-level integration. Several page components watching different locale refs and writing document.documentElement.dir can compete during navigation. A locally English component should set a local boundary rather than changing the whole document.

Connect language controls to the global Composer#

The earlier setup uses legacy: false, which enables Vue I18n's Composition API mode. Read and update the global Composer when switching the whole application:

vue
<script setup lang="ts">import { useI18n } from 'vue-i18n';const { locale, t } = useI18n({ useScope: 'global' });</script> <template>  <main>    <h2>{{ t('queueTitle') }}</h2>    <button type="button" lang="ar" @click="locale = 'ar'">العربية</button>    <button type="button" lang="en" @click="locale = 'en'">English</button>  </main></template>

Use this as a small App.vue probe with the previous entry. Vue templates unwrap the exposed ref, so the assignments update the Composer's locale. Confirm that the heading, root language and root direction change together.

Vue I18n distinguishes global and local locale scope. A component with local messages can obtain a local Composer, and changing that local locale does not change the application's global locale. The Composition API guide documents explicit useScope selection. Inspect which Composer a language control actually changes when one panel translates but the document remains unchanged.

Do not infer direction from whichever fallback message happens to render. An untranslated label falling back to English does not make the surrounding Arabic interface LTR. Fix the missing message while retaining the resolved document locale.

If messages load asynchronously, load the requested bundle before presenting that locale as ready. Vue I18n's lazy-loading guide shows the relevant loading and locale APIs. Handle a failed load and rapid consecutive selections explicitly; an older request finishing later must not restore an earlier language choice.

For regional locales, make the mapping explicit in the supported configuration. A route locale, a document language tag and a component library's import name may use different identifiers. Normalize them at that integration boundary. The two-locale demonstration does not recognize every regional Arabic tag, and silently treating an unsupported identifier as English would conceal a resolution error rather than fix direction.

Keep derived direction reactive when passing it down#

A component API may require a direction prop even though the document already has dir. Derive that prop from the same locale ref. This setup-body assignment, using the global locale ref from the earlier example, takes a snapshot:

ts
// Problem: this expression runs once during setup.const direction = locale.value === 'ar' ? 'rtl' : 'ltr';

The heading can translate after a switch while a child receiving that plain string keeps its initial direction. Recreating the child might conceal the snapshot and reset its state at the same time.

Use a computed value for the changing relationship. This small component makes the resulting attribute inspectable:

vue
<script setup lang="ts">import { computed } from 'vue';import { useI18n } from 'vue-i18n';const { locale } = useI18n({ useScope: 'global' });const direction = computed(() => locale.value === 'ar' ? 'rtl' : 'ltr');</script> <template>  <section :dir="direction"><slot /></section></template>

The computed-properties guide explains dependency tracking. Keep the computation free of document writes; the application-level watcher owns that side effect. In the product, pass this derived value only where a component's contract needs it, and use the shared locale metadata when expanding beyond the demonstration's two languages.

Inspect the child's received prop as well as its rendered attribute. A child that copies an initial prop into unrelated local state can retain the old value even when the parent updates correctly. Vue's props guide describes the reactive input boundary. Test a switch on the existing instance before deciding that a forced remount is required.

Scoped styles still need logical properties#

An SFC's scoped CSS limits where selectors apply. It does not turn physical spacing into direction-relative spacing. This rule in the equipment-service component remains left-sided on an Arabic page:

css
/* Problem: rules inside the component's <style scoped> block. */.service-notes {  padding-left: 26px;  border-left: 2px solid #476b75;}

If the notes are indented and marked at reading start, replace those declarations in the same component:

css
.service-notes {  padding-inline-start: 26px;  border-inline-start: 2px solid #476b75;}

The English indentation and border stay on the left. Horizontal RTL maps the relationship to the right. The logical-properties specification defines the mapping; Vue's SFC CSS reference explains scoped selector transformation. These are separate mechanisms.

R030 covers direction-sensitive physical properties without an RTL override. Include styles bound through :style in the review: an object containing marginLeft still expresses a physical margin. Vue's class and style bindings render the supplied style values; they do not provide an RTL conversion step.

Check the element's own computed direction when a component contains a local LTR region. Logical properties follow that element's direction, which may differ from the page. Remove the old physical declarations when converting a rule so they cannot compete with the replacement.

Transforms need a separate decision. A translateX() value in a Vue transition is a physical movement, even if the component's padding is logical. Review entering and leaving states and any library-supplied animation. The Transition guide explains the lifecycle classes; it does not choose the product's intended movement direction. Keep physical diagrams and telescope orientation indicators fixed when their meaning requires it.

When a scoped repair appears to have no effect, inspect the generated selector and the winning declaration in developer tools. Check whether the class reaches the component's own element or a library's internal node. Disabling scoping globally can make an experiment appear successful while exposing unrelated components to the rule. Identify the intended styling boundary and the component's supported customization API before broadening a selector.

Verify that component attributes reach the intended element#

Passing dir to a Vue component is not the same as inspecting a native element with that attribute. Vue can forward undeclared attributes to a single root, but a component with multiple roots needs an explicit destination. A declared prop must also be used by the component's implementation.

This matters when a technical field sits beneath an Arabic label. If LTR direction lands on a wrapper, it can affect the label too. If a multi-root field never forwards it, the native input can remain RTL.

Here is a custom field with an explicit forwarding contract:

vue
<!-- ManualUrlField.vue, Vue 3.4+ --><script setup lang="ts">defineOptions({ inheritAttrs: false });defineProps<{ id: string; label: string }>();const value = defineModel<string>({ required: true });</script> <template>  <label :for="id">{{ label }}</label>  <input :id="id" v-model="value" type="url" v-bind="$attrs"></template>

Use it from a parent that owns the value:

vue
<script setup lang="ts">import { ref } from 'vue';import ManualUrlField from './ManualUrlField.vue';const manualUrl = ref('https://manuals.example.org/observatory/focuser-care');</script> <template>  <ManualUrlField id="equipment-manual" v-model="manualUrl" dir="ltr"    label="رابط دليل العناية بالجهاز" /></template>

The label remains in the surrounding Arabic context, while the input receives the caller's dir. The parent supplies the value and the Arabic label; use an application message for that label in the bilingual product. Vue documents attribute fallthrough and the component model API separately.

This field deliberately forwards remaining attributes to the input. A broader component might need to split wrapper classes, native attributes and event listeners into a different API. Avoid forwarding everything to every root merely to remove a warning.

Inspect the rendered input, label association and computed direction. Test editing, selection, validation and an empty value. R070 covers telephone, email and URL inputs rendered RTL; ordinary Arabic service notes should retain their Arabic input direction. See Arabic text input direction for those field-specific choices.

Teleport preserves component context, not DOM inheritance#

Teleport moves rendered nodes to another DOM location while preserving their logical Vue relationship. Props, emitted events and injection can still work, even when inherited browser direction changes.

The failure is easiest to reproduce in an Arabic preview embedded within an LTR host. A note looks RTL inside its wrapper, but Teleport places it under body, outside that wrapper. Put the direction boundary on the moved content when it needs to retain the preview's direction:

vue
<!-- LocalNotePreview.vue: a modeless preview, not a modal dialog. --><script setup lang="ts">import { ref } from 'vue';const props = defineProps<{ direction: 'ltr' | 'rtl' }>();const showNote = ref(false);</script> <template>  <section :dir="props.direction">    <button type="button" @click="showNote = true">عرض ملاحظة الصيانة</button>    <Teleport to="body">      <aside v-if="showNote" :dir="props.direction" lang="ar"        class="service-note" aria-labelledby="service-note-title">        <h3 id="service-note-title">مراجعة آلية التركيز البؤري</h3>        <p>أرفق نتيجة الفحص قبل إعادة الجهاز إلى جدول الرصد.</p>        <button type="button" @click="showNote = false">إخفاء الملاحظة</button>      </aside>    </Teleport>  </section></template>

Pass direction="rtl" when mounting this Arabic fixture beneath an LTR host. To reproduce the failure, remove only the aside's direction binding, open the note and inspect its actual DOM ancestry. The component's wrapper does not become the aside's DOM ancestor merely because it surrounds Teleport in the template.

On a fully Arabic document, teleported content can inherit root direction without a redundant local override. The explicit binding is useful for the local preview contract. Vue's Teleport documentation explains the separation between rendered DOM and logical component hierarchy.

Ancestor-dependent CSS needs the same review. A selector requiring the note to sit beneath the preview wrapper cannot match that relationship after the move. Do not assume every scoped rule disappears: inspect the actual selector and DOM relationship. Use a class on the teleported content or a target-specific boundary for rules that should apply there.

Test opening, closing and direction changes while the note is visible. For an actual modal, use the application's dialog implementation with its focus management, dismissal and focus-return behavior. Adding role="dialog" to this modeless demonstration would not implement those interactions.

Isolate interpolated identifiers without rebuilding the sentence#

Vue interpolation escapes text; it does not isolate its bidirectional behavior from surrounding text. A service reference beginning with digits and ending with Latin letters needs its stored group order preserved inside an Arabic sentence.

This template puts the identifier directly into that sentence:

vue
<script setup>const reference = '314829-LENS';</script> <template>  <p>ملف صيانة الجهاز: {{ reference }}</p></template>

The intended reading is the Arabic label followed by one intact technical identifier. Keep the value's direction boundary separate from the translated sentence. The earlier message catalog already defines serviceRecord with a named placeholder in each language:

vue
<script setup>const reference = '314829-LENS';</script> <template>  <i18n-t keypath="serviceRecord" tag="p" scope="global">    <template #reference>      <bdi dir="ltr">{{ reference }}</bdi>    </template>  </i18n-t></template>

The i18n-t component is installed by the earlier Vue I18n plugin setup. Its named slot keeps the identifier as an element while allowing each complete message to place it where the translation requires. Vue I18n documents this component interpolation.

The W3C inline-bidi guidance explains why the boundary belongs around the foreign value. Do not put the Arabic label inside the same LTR boundary. For a value whose direction is unknown, choose the boundary from its content contract instead of forcing every interpolation to LTR.

R021 covers unisolated bidi hazards, including Latin tokens inside Arabic text. Test the actual rendered identifier and adjacent punctuation in the browser. A correct copied value does not establish that its visual group order is correct. Use Arabic and English mixed text for deeper bidi cases.

Keep interpolated text as text. Vue's template syntax reference distinguishes ordinary interpolation from raw HTML rendering. Avoid replacing the slot with a concatenated v-html string merely to insert an isolation element.

Preserve record identity and user state when direction changes#

Do not reverse the service-record array just to put its first item on the right. Normal horizontal flex layout already follows direction. A data reversal changes the sequence the application renders, which is a different operation from changing its inline starting edge.

Keep v-for keys tied to stable equipment or service identifiers. Vue's list-rendering guide explains how keys preserve node identity when updating lists. A translated label or array index is a poor substitute when records contain editable notes or component state.

Avoid making the entire service form's key depend on locale unless resetting it is an intentional product decision. A remount can make a stale widget appear fixed while discarding unsent fault descriptions, selection and focus. Test a language change with a partially completed service note and the same record selected afterwards.

Translate error reasons when rendering rather than storing only an already translated sentence. An error created in English can otherwise survive beneath the Arabic interface until validation runs again. This is application state to review, not something document direction can repair.

Configure the component library at its own boundary#

A native Vue component and a library date picker do not necessarily obtain direction from the same source. Identify whether the library uses inherited HTML direction, a provider, a locale service or a generated stylesheet.

For example, Vuetify's internationalization documentation connects component directionality with its locale service and describes integration with Vue I18n. Check the installed Vuetify major's configuration rather than copying an older global RTL option. Other libraries have different contracts; consult PrimeVue's RTL guidance for its direction support.

Keep library locale, application messages and document direction synchronized from the same resolved choice. Importing Arabic application messages does not establish that a library's pagination captions or picker controls are Arabic. Inspect its translated component text separately from its layout.

Test the components the service queue actually uses: an expanded equipment selector, an open scheduling picker and a notification after a failed update. Check keyboard behavior, popup direction and long translated labels. Inspect the rendered popup when a library uses Teleport internally.

Use a native-component probe to narrow failures. If a normal input follows the root and one library widget does not, inspect that widget's provider and internal element before changing the document again. Avoid overriding private selectors to compensate for an unconfigured provider; such rules can apply a second correction once the provider is fixed.

Render the initial direction on the server#

The browser entry shown earlier accesses document and creates one browser application instance. Server rendering needs a different lifetime and a server-owned document template.

Resolve the request's locale before rendering. Create request-specific Vue and i18n instances, use that locale for component output, and emit matching lang and dir attributes in the document. Initialize the browser with the same resolved locale for hydration.

Vue's SSR guide covers platform-specific APIs, shared state across requests and hydration mismatches. A mutable module-level locale shared by server requests can allow one request's language choice to affect another. Do not reuse the browser singleton pattern as request-specific server state.

An onMounted correction can change the interactive page but cannot establish that the original server response was Arabic and RTL. Compare the response HTML with the hydrated DOM. Test an Arabic deep link directly, then repeat English and Arabic requests in both orders.

Include an empty browser session in this check. A language bundle or saved preference from an earlier visit can make a client navigation pass while a new visitor receives a different initial state. Capture the resolved locale, response attributes and first rendered heading for the same request. If the response and browser disagree, repair the locale handoff instead of suppressing the hydration warning.

Teleport has additional SSR handling. The server renderer exposes teleported content separately for insertion into the output; follow the SSR integration's target and hydration requirements. The client-only preview's to="body" demonstration is not an SSR integration recipe.

Keep this work in the application's existing SSR or document-management layer. A page component that independently writes root attributes can compete with a framework's head manager during navigation. Verify the final response and navigation behavior rather than adding another writer when the values disagree.

Verify the rendered DOM and the complete service journey#

Check one saved service record across both languages. Include unsent observations, a technical URL, a mixed-content reference and an open preview so the test reaches the boundaries shown here.

  • Load Arabic directly and inspect the initial document language and direction.
  • Switch languages through the global Composer and verify the heading and attributes together.
  • Inspect computed logical spacing on ordinary components and locally different-direction content.
  • Confirm that custom field attributes reach the native input while its label keeps the intended context.
  • Open teleported and library-owned content and inspect its DOM direction separately.
  • Verify the identifier visually, then test editing and validation without losing the selected record.
  • Repeat at narrow widths, after fonts load and against the production build.

Wait for Vue's DOM update before asserting rendered content after reactive changes. The nextTick API provides that boundary. A completed Vue update does not mean that a transition, font load or third-party popup has finished; wait for the relevant state when the assertion depends on it.

Use component tests for attribute forwarding and state preservation, then verify browser layout through the deployed interface. Vue's testing guide distinguishes those test boundaries. A DOM assertion that an input has dir="ltr" cannot show whether an Arabic helper message is clipped, and a screenshot cannot establish that editing kept the correct service record selected. Test those outcomes with the evidence each requires.

Record the locale source, rendered element, computed direction and winning style when a failure remains. Those details distinguish a local Composer from a document problem, a missing attribute binding from an input problem, and a Teleport boundary from a scoped selector problem.

A free Ritla scan of the Arabic service page can surface direction-sensitive physical properties without RTL overrides and unisolated bidi hazards in template output. Continue with Arabic and English mixed text when interpolated values need attention, or Arabic text input direction when a custom field's editable value still behaves incorrectly.

Checks in this guide

See what your Arabic pages are hiding

Paste a URL. Ritla renders the page on desktop and mobile, runs every check, and shows the top issues with screenshot evidence.

Scan a page freeBrowse the checks