Change direction with selecting Language in Vuejs

Viewed 1056

I have a Language select-option. If I choose Arabic then it will change the direction.

* {
  direction: rtl!important;
}

While I am using this, then the whole direction changed to right to left. But how can I do that with Methods?

methods: {
  languageSelection() {
     if(this.lang == 'arb') {
        document.getElementsByTagName("*")[0].style.direction = "rtl!important";
        document.getElementsByTagName("html")[0].style.direction = "rtl!important";
        document.getElementsByTagName("body")[0].style.direction = "rtl!important";
      }
   }
}

The above code is not working! If I can add a CSS file then it will be better for me. For example:

languageSelection() {
  if(this.lang == 'arb') {
     // active a css file like: style-rtl.css
  }
}

But how is this possible?

3 Answers

Ok. So when you use getElementsByTagName("*")[0] you will probably get a handle to a <html> element. So the same element you're accessing in the next line.

To change all elements direction you would have to iterate over the collection:

const elems = document.getElementsByTagName("*")
for (let elem of elems) {
    elem.style.direction = 'rtl'
}

But this will still include <script>, <style>, <meta> tags, which is not the best solution.

My solution

I would create class in the css

html.is-rtl * {
    direction: rtl;
}

then just toggle the class when you select the language which is read from right to left.

languageSelection() {
  if (this.lang == 'arb') {
     document.querySelector('html').classList.add('is-rtl')
  }
}

Could create a stylesheet and append it to the head:

languageSelection() {
  if(this.lang == 'arb') {
     const style = document.createElement('style');
     style.innerHTML = `*{direction:rtl!important}`;
     document.head.appendChild(style);
  }
}

You should manage it inside App.vue. add custom css class based on chosen language to #App element.

<template>
  <div id="app" :class="{'dir-rtl': isRtl}">
    ...
  </div>
</template>
<script>
export default {
  computed: {
    isRtl () {
      return this.lang === 'arb'
    }
  }
}
</script>
<style lang="scss">
.dir-rtl {
  direction: rtl !important;
}
</style>

best place to save and change lang is vuex store.

Related