Vue-router: CSS Modules and `router-link` active classes. Add data-attribute flag

Created on 14 Jan 2018  路  3Comments  路  Source: vuejs/vue-router

Version

3.0.1

Reproduction link

https://codesandbox.io/s/w024ro0695

Steps to reproduce

The following styles won't work as ad-hoc classes won't apply styles when parsed:

<template>
  <div>
    <router-link :class="$style.myLink" to="/foo">Hello</router-link>
  </div>
</template>

<style module>
.myLink {
  color: #f00;
}

// This won't do anything
.myLink.router-link-exact-active {
  color: #0f0;
}
</style>

What is expected?

This is to be expected but an alternative to classes would be great

What is actually happening?

As expected, but an alternative to classes (eg. data attributes) would be great


AFAIK it's not possible to reference the classes from within the context of CSS modules.

It would be great if there was instead a flag on the router to use data attributes to flag active links so that you can have conditional CSS module states for links. Eg.

// router.js
export default new Router({
  linkActiveDataAttributes: true
})

Would add the active attributes as data to the router-link's in the application:

<router-link to="/" :class="$style.myLink">Foo</router-link>

// would convert to

<a href="/" data-active="true" data-exact="true" :class="$style.myLink">Foo</a>

// and i can write css modules as
.myLink[data-exact] {
  color: #f00
}

Most helpful comment

https://codesandbox.io/s/9lxyr4xk7y

You can set which class to use for active links (and similarly, for exact-active).

https://router.vuejs.org/en/api/router-link.html

All 3 comments

https://codesandbox.io/s/9lxyr4xk7y

You can set which class to use for active links (and similarly, for exact-active).

https://router.vuejs.org/en/api/router-link.html

Ah awesome. Can we get that added to the docs somewhere? Or is it too specific to be in the general docs?

what if i have two routes with the same name and only differs in query string. How can i make this work. For my experience, this doesn't. Then i maybe need a :class attr. I maybe wrong, waiting your response

Was this page helpful?
0 / 5 - 0 ratings