How to load css file dynamically

一世执手 提交于 2019-12-23 18:32:16

问题


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


回答1:


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>



回答2:


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


来源:https://stackoverflow.com/questions/52767025/how-to-load-css-file-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!