Is it possible to import css file conditionally in Vue.js?

大城市里の小女人 提交于 2021-01-20 07:21:08

问题


I have my admin-panel and pages for clients in one Vue.js project. Is it possible to use certain css-files only if the current route has "forAdmin" meta?


回答1:


By using style-loader with the useable API, you can dynamically apply and remove a stylesheet in your code.

First you'll need to update your webpack config rules so that stylesheets with the .useable.css extension will be loaded with the useable API:

{
  test: /\.css$/,
  exclude: /\.useable.css$/,
  use: [
    'style-loader',
    'css-loader'
  ]
},
{
  test: /\.useable\.css$/,
  use: [
    'style-loader/useable',
    'css-loader'
  ]
}

Now in your router code file, you can import your stylesheet and .use() and .unuse() it according to your condition:

import style from './admin.useable.css'

const router = new VueRouter(...)

router.afterEach((to, from) => {
  for (const route of to.matched) {
    if (route.meta.forAdmin) {
      style.use()
    }
  }

  for (const route of from.matched) {
    if (route.meta.forAdmin) {
      style.unuse()
    }
  }
})

Make sure you balance the total number of .use() and .unuse() calls correctly because a reference count is maintained behind the scenes to figure out when the stylesheet should be applied.

I'm not sure what your setup is, so there might be a better way of doing what you want though.




回答2:


In your mounted() function you can add it like this.

if(someCondition) {
    var element = document.createElement("link");
    element.setAttribute("rel", "stylesheet");
    element.setAttribute("type", "text/css");
    element.setAttribute("href", "external.css");
    document.getElementsByTagName("head")[0].appendChild(element);
}


来源:https://stackoverflow.com/questions/56703038/is-it-possible-to-import-css-file-conditionally-in-vue-js

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