Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 465
Fabio Zanchi Avatar asked Oct 21 '25 12:10

Fabio Zanchi


2 Answers

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).

like image 71
Jalasem Avatar answered Oct 23 '25 02:10

Jalasem


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

<script>
export default {
  head: {
    link: [
      {
        rel: "stylesheet",
        href: "/about.css"
      }
    ]
  }
};
</script>
like image 42
TenshiGoan Avatar answered Oct 23 '25 01:10

TenshiGoan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!