Fabio Zanchi
Fabio Zanchi

Reputation: 945

How to use dynamic CSS files with Nuxt?

I'm working in a project that have different users with their logos. Based on the API call I want to load a different CSS with different colour palette.

Now I have a css folder inside assets folder with main.js (with my custom font styles, etc) and another files in there for the custom color palette: <color-name>-palette.css.

In my nuxt.config I'm calling the CSS colour like that:

  css: [
    '~/assets/style/app.styl',
    '~/assets/css/main.css',
    '~/assets/css/orange-palette.css'
  ],

Is there any way to bind the CSS file depending on the URL path/API call instead of putting the path there?

I'm not sure if I can use it on templates as well, binding the CSS files in there. Is it possible?

Thanks

Upvotes: 4

Views: 7269

Answers (2)

Jalasem
Jalasem

Reputation: 28451

To load CSS files dynamically, use head() instead of head: {}. That way, the values can be dynamic. Take a look the code below with working demo at https://codesandbox.io/s/l4on5508zm

<template>
  <section>
    <h1>Index</h1>
    <button @click="swap">swap</button>
    <p v-text="cur" />
  </section>
</template>

<script>
export default {
  head() {
    return {
      link: [
        {
          rel: "stylesheet",
          href: `/${this.cur}.css`
        }
      ]
    };
  },
  data() {
    return {
      cur: "light"
    };
  },
  methods: {
    swap() {
      if (this.cur === "light") {
        this.cur = "dark";
      } else {
        this.cur = "light";
      }
    }
  }
};
</script>

Looking at the code snippet above, you can bring in the css file to use on your page dynamically via the head() function. You can change the CSS to be used on the fly right on any page based on user interaction (for instance my button click interaction).

Upvotes: 8

TenshiGoan
TenshiGoan

Reputation: 506

You can use "head" in page component. https://codesandbox.io/s/xr55o4yqmq

<script>
export default {
  head: {
    link: [
      {
        rel: "stylesheet",
        href: "/about.css"
      }
    ]
  }
};
</script>

Upvotes: 2

Related Questions