Brady Dowling
Brady Dowling

Reputation: 5522

Configure Nuxt to include CSS by route or page, not globally

The Nuxt documentation has instructions for including CSS globally, which is quite helpful. It would also be helpful if there was a way to include a .scss file for just certain routes.

For example, is there a way to include new.scss for all routes /new/* and old.scss for all routes /old/*? Or simply to include CSS on a whole page e.g. /new and not necessarily all its children. This would also achieve my purposes.

I was initially thinking that this would be done via nuxt.config.js but perhaps this can be done within the actual .vue file of the page itself.

Upvotes: 1

Views: 4586

Answers (3)

Michal Levý
Michal Levý

Reputation: 37793

Nuxt is using vue-meta so you can include CSS on individual page like this:

// inside your page
export default {
  head () {
    return {
      meta: {
        link: [
          { rel: 'stylesheet', href: '/css/new.css' },
        ]
      }
    }
  }
}

Since it is a function, it should be no problem to make it dynamic/per-route

// inside your page
export default {
  head () {
    if($route.path.includes('/old/')) {
      return {
        meta: {
          link: [
            { rel: 'stylesheet', href: '/css/old.css' },
          ]
        }
      }
  }
}

You can also extract this into a mixin and apply it easily to multiple pages....

Upvotes: 6

sha
sha

Reputation: 157

Another clean way in using different layout and add various css files on each of them. So the pages which follow different layout can have different style.

Upvotes: 0

Brady Dowling
Brady Dowling

Reputation: 5522

One method of doing this is to just import your CSS into the (non-scoped) style section of the Vue component for your page. For example, within pages/old/index.vue you could have the follow

<style>
@import '~/assets/scss/old.css';
</style>

Note, again, that the style tag here is not scoped. This is key to making this work as scoped styles will not apply to child elements (with the exception of the root element of the child component).

Upvotes: 7

Related Questions