This technique works when you make the static menu. In my case, I generated a dynamic menu, according to the routes I have in my rotas.js
file it is responsible for the declaration of routes in my system, hence I import it into a main component (< strong> App.vue
) and within this file I pass the routes as property to the sidebar.vue module, the menu is based on the number of existing routes, in your example the menu is static so your example applied perfectly, since I could not dynamically pass the property this way on the HTML attribute , since it is in a loop of v-for
.
Anyway, I've got a solution for that. Here's how I did it.
In documentation of vue.js they teach to pass a object to the class
property and then on this object the active
property responsible for applying the class active
to my HTML element checks whether the isActive
is true ( true
) and hence applies or not, once I understood this, I decided to transform the attribute into a function and pass it the value of the rota.path
attribute that is running on time the loop is made.
An error that has occurred at this time is that when rota.path
received the value of the initial route ''
, it did not apply any class to the element, since the value is "empty". So I did a ternary check and if the value was empty or ''
the parameter passed to isActive
would be /
, causing the function to return true
and the Home Page link worked just like the rest.
My HTML looks like this:
<li v-for="rota in rotas" :class="{ active: isActive(rota.path ? rota.path : '/') }">
<router-link :to="rota.path ? rota.path : '/'">
<i :class="rota.icone"></i>
<p>{{ rota.titulo }}</p>
</router-link>
</li>
and my JavaScript code looks like this:
<script>
props:['rotas'],
data(){
return{
isActive: function(path){
if(this.$route.path == path){
return true;
}
}
}
}
</script>
In this way it is active in all links that have routes and also in HOME which in this case is an empty route.
In the case of the rotas
property, it is because I get your data from another component.
My route file (routes.js) is basically like this:
import Home from './modulos/pages/Home.vue';
import Conta from './modulos/pages/Conta.vue';
import Perfil from './modulos/pages/Perfil.vue';
export const routes = [
{path:'', component: Home, titulo: 'Home', icone: 'pe-7s-graph' },
{path:'/conta', component: Conta, titulo: 'Conta', icone: 'pe-7s-user'},
{path:'/perfil', component: Perfil, titulo: 'Perfil', icone: 'pe-7s-user'}
];