4

I'm using Vue.js with vue-i18n to switch languages on my project without the need to refresh. However, when i want to switch between Arabic and anything else i need to change the website's design from (right to left) to (left to right) or vice versa.

It is currently made so that i would need a refresh to load my rtl.scss file:

This is the code that loads css on refresh:

let locale = VueCookie.get('locale') || 'en'
if (locale === 'ar') {
  require('rtl.scss')
}

This is the code that makes the page refresh:

if (newLocale === 'ar' || oldLocale === 'ar') {
  window.location.reload()
}
Omar Samman
  • 573
  • 5
  • 12
  • 4
    one way is to add/remove a class to `` and use different CSS based on different body class – Jacob Goh Aug 04 '18 at 07:19
  • this wont work !! you will have to add a class to the app root element and style it accordingly. or you will have to manually append a `` tag to body with plain js – shakee93 Aug 04 '18 at 07:19
  • 1
    @shakee93 thanks man I tried it before and it didn't work for me. – Omar Samman Aug 04 '18 at 07:34

2 Answers2

6

Going off of Jacob Goh's comment you can do the following:

Change your first snippet to:

require('rtl.scss')
let locale = VueCookie.get('locale') || 'en'
if (locale === 'ar') {
  document.querySelector('body').classList.toggle('rtl');
}

and ur second to:

if (newLocale === 'ar' || oldLocale === 'ar') {
  document.querySelector('body').classList.toggle('rtl');
}

finally edit your rtl.scss file to:

body.rtl {
  /* Old scss */
}
Issam Rafihi
  • 432
  • 3
  • 10
0

A simple alternative to the accepted solution:

const {t, locale} = i18n.global;

watchEffect(() => {
    document.dir = t('text_direction');
    document.documentElement.lang = locale.value;
})

Requires adding a text_direction property to each language (at least in the fallback language if you have one), valued as either rtl or ltr. whenever the locale changes, this will update the root document element to the proper direction for the current language.

You may then write your CSS to depend on that property if that is necessary.

This avoids having a condition for every language that requires a different direction.

Elon61
  • 1
  • 1
  • 1