Route based CSS with Vue.js

November 9, 2020

Vue.js is very flexible when it comes to adding CSS.

We can use a dedicated stylesheet, use the <style> section of a single file component, inline styles, libraries etc. A common way of binding styles is to add a style object as a data property, as we have here:

<template>
  <div id="app">
    <p :style="cssObj">Account page</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cssObj: {
        fontSize: "24px",
        color: "red",
      },
    };
  },
};
</script>

This is especially useful if the font size and color were dynamic, maybe passed down via props, or computed based off another value.

If we had multiple css objects we can also pass them in as an array:

<template>
  <div id="app">
    <p :style="[cssObj, baseStyles]">Account page</p>
  </div>
</template>

We can also conditionally render styles based on the current route, using the Vue router. If you do not already have the router package installed, you can install using these steps:

https://next.router.vuejs.org/installation.html

Please note, this is Vue Router v4 which is to be used with Vue 3.

This then gives us access to the current route information using $route in our template:

<template>
  <div id="app">
    <p :style="[cssObj, baseStyles]">Account page</p>
    {{ $route }}
  </div>
</template>

$route gives us information such as the current path, and we can use this in combination with the Javascript ternary operator to add any CSS styles based on the current route:

<template>
  <div id="app">
    <p
      :style="[
        cssObj,
        $route.path.startsWith('/account')
          ? 'border: 1px dotted red;'
          : 'border:none;',
      ]"
    >
      Account page
    </p>
  </div>
</template>

This will now always apply our cssObj styles, but will then only apply the border if the current route begins with /account.

Also, this style attribute can also be placed at the top level of our app too, not just on a single page. We could maybe use it to check if the user is on a not found page, or if the user is logged in and apply styling based on this.

Another use case could be if the same component was used multiple times, but we wanted to make some small CSS changes based on the route, although this could also be achieved using non-prop attributes too.