简体   繁体   中英

How to load css file dynamically

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

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> 

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM