vuejs / router

🚦 The official router for Vue.js
https://router.vuejs.org/
MIT License
3.88k stars 1.18k forks source link

Introduce `elementTargetClass` option (alternative to `:target`) #2231

Closed AlttiRi closed 4 months ago

AlttiRi commented 4 months ago

What problem is this solving

While it supports scrolling to a hash:

export const router = createRouter({
    history: createWebHashHistory(), // createWebHistory
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (to.hash) {
            return { el: to.hash };
        }
    }
});

Setting the hash with History API do not affect on styling the element with :target selector.

Proposed solution

Add a new createRouters option similar to

For example:

export const router = createRouter({
    /* ... */
    elementTargetClass: "router-target-element"
});

Describe alternatives you've considered

No response

posva commented 4 months ago

And what does this option do?

AlttiRi commented 4 months ago

Adds the class ("router-target-element" from the example above) to the element with the id the same as the URL's hash. So, it can be used as an alternative to :target CSS selector which does not work with vue-router.

:target, .router-target-element {
  font-weight: bold;
}

For example, the route /main#1 will add the router-target-element class to the element with id 1.

posva commented 4 months ago

I see, so it's specific to the web hash history and what you mentioned on #2230. It can be solved by creating that custom history you proposed, which seems more appropriate than introducing a new option that only applies to a specific history mode.

AlttiRi commented 4 months ago

it's specific to the web hash history

No, this applicable to both createWebHistory and createWebHashHistory. With createWebHistory mode the :target CSS selector does not work too.

> Setting the hash with History API do not affect on styling the element with :target selector.


I'm not the only one who faced this issue:

So, it can be simple fixed with the similar option as linkActiveClass and linkExactActiveClass.

posva commented 4 months ago

Thanks for pointing out #2076 , I forgot about it being a spec limitation. You should follow https://github.com/w3c/csswg-drafts/issues/6942 for a proper implementation of this.

You can implement the feature in many ways. The most reusable one would be a custom Router Link by checking the current route and the this custom link resolved route's hash