7

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?

2
  • Are you using webpack? Commented Jun 21, 2019 at 12:16
  • @DecadeMoon yes Commented Jun 21, 2019 at 12:26

2 Answers 2

6

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I was thinking something like you answered. Thanks
How about SCSS files? they need to be compiled
5

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 Comments

if I would do that in webpack config. Does it works when it is in production? thanks thanks :) I like the idea here, but is this a good way, interchanging themes? thanks thanks
I don't see a reason why it wouldn't work in production, provided that the production CSS loaders are the same as for development. It won't work if you are doing something different in production, like extracting the CSS to a file.

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.