11

We are using Vue.js and Vuetify for my application. As part of my application, I will make API call on page load based on that API response entire application will render all the components. As part of this API, I will get property named as cssDirection and it tells which css file suppose to load either it's LTR or RTL.

When I worked in Angular, We used this approach.

Now my question is there any workaround to achieve this in Vue instead of the above approach ? I googled I didn't find any solutions.

Thanks

4 Answers 4

24

To load css file dynamically you can do somethings like this

<template>
  <div>
    <button @click="appendFile">Click me to add css file</button>
  </div>
</template>

<script>
export default {
  methods : {
    appendFile(){
      let file = document.createElement('link');
      file.rel = 'stylesheet';
      file.href = 'myfile.css'
      document.head.appendChild(file)
    }
  }
}
</script>

Sign up to request clarification or add additional context in comments.

Comments

3

Injecting a <link> into the page also works in vue, an alternative is to use webpack's code splitting.

if (data.rtl) {
  import("./css/rtl.css")
} else {
  import("./css/ltr.css")
}

2 Comments

Does it work with loading CSS file from an external source like a CDN?
Not out of the box, there are plugins for that openbase.io/js/webpack-external-import but unless it happens frequently in your codebase i'd suggest adding it manually to the dom like the other answer suggest
3

Use import("") to load the static css from assets, for example if are you using multiple files for styling:

On App.vue:

<script setup>
import { useStore } from "vuex";
import { computed, watchEffect } from "@vue/runtime-core";

const store = useStore();
const theme = computed(() => store.state.theme);

watchEffect(() => {
  import(`./assets/css/themes/${theme.value}.css`);
});
<script/>

Comments

0

You can use:

import(path);
in lifecycle 

And set your file name dynamically in data, for example:

data(){
   return{
      filename: 'test1',
   }
}
created(){
import(`./assets/css/themes/${this.filename}.css`);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.