Skip to content
Advertisement

Vue.js: Add router-link-active to vue-router component loaded for root

I’m having some trouble with vue-router. My routes are set up like this:

const routes = [
    { path: '/', component: a },
    { path: '/a', component: a },
    { path: '/b', component: b },
    { path: '/c', component: c }
]

As you can see, I want to load component a when the page loads. But I don’t want the URL to change to /a when the page loads. However I would like to trigger the router-link-active-class on the <router-link> related to the a component, even though I’m still at /.

I’ve tried with some simple JS like:

if(window.location.hash === '#/') {
    var el = document.querySelector('#drawerList').firstElementChild;
    el.className += 'router-link-active';
}

However vue is not removing the class again when I click on the link to /b or /c. Can any of you hint me in the corrent direction?

Advertisement

Answer

You can manually bind class to router-link like this

<router-link :class="{'router-link-active': $route.fullPath ==='/' || $route.fullPath === '/a'}" to="/a"></router-link>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement