Defining page direction dynamically - Vue Js

Viewed 993

I'm trying to set the page direction (RTL or LTR) dynamically on my Vue js project.

However, if I try to set dynamically, e.g using a variable called direction, nothing happens (it keeps the standard value, LTR value):

  <html lang="en" v-bind:dir="direction" id="example-1">
    <head>
     <title>Page Title</title>
    </head>
    <body>
      <div>
        <p>Write this text right-to-left!</p>          
      </div>
   <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"> 
   </script>
   <script src="test.js"></script>
   </body>
 </html>

var test=new Vue({
el: '#example-1',
data: {
    counter: 0,       
    direction:'rtl'
  },
  methods: {
    greet: function (event) {
        this.direction='rtl';
    }
}
});

Shows the following error, [Vue warn]: Do not mount Vue to or - mount to normal elements instead. How can I do that?

2 Answers

Try mounting in the div instead of the html element. And use CSS direction

  <html lang="en">
    <head>
     <title>Page Title</title>
    </head>
    <body>
      <div v-bind:style="{direction}" id="example-1">
        <p>Write this text right-to-left!</p>          
      </div>
   <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"> 
   </script>
   <script src="test.js"></script>
   </body>
 </html>

Like @Steven Spungin pointed out, you should mount your Vue app in div instead of the html element.

Then you can handle your page direction dynamically in a function like this :

...
methods:{
    ...
    setPageDirection(dir){
        document.body.style.direction = dir
    }
    ...
}
...

You can find more ways to set page direction on this thread : Direction rtl to all page

Related