Sam Stevenson
Sam Stevenson

Reputation: 95

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

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?

Upvotes: 7

Views: 11140

Answers (2)

Decade Moon
Decade Moon

Reputation: 34306

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.

Upvotes: 5

user5283119
user5283119

Reputation:

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

Upvotes: 6

Related Questions