I have link something like this:
<li class="list-item active"> <router-link :to="{name:'link-1'}"> Link 1</router-link>
<li class="list-item"> <router-link :to="{name:'link-2'}"> Link 2</router-link>
I want to add class active with list-item class based on the url suppose if the url is localhost:8000/link-1 then link-1 should be active.
If you are using Vue Router > 3.1.0 you can use <router-link> and a scoped slot for this:
<router-link
:to="{name:'link-1'}"
v-slot="{ href, route, navigate, isActive, isExactActive }"
>
<li
:class="[isActive && 'active', isExactActive && 'exact-active']"
>
<a :href="href" #click="navigate">Link 1</a>
</li>
</router-link>
<router-link
:to="{name:'link-2'}"
v-slot="{ href, route, navigate, isActive, isExactActive }"
>
<li
:class="[isActive && 'active', isExactActive && 'exact-active']"
>
<a :href="href" #click="navigate">Link 2</a>
</li>
</router-link>
If you don't need to have .active on the li elements, <router-link> has this build in. (See Dan's awnswer)
Vue router provides this functionality. When a link is active, it will have the router-link-exact-active class applied.
In your CSS:
.router-link-exact-active {
// styles here
}
There is also router-link-active which would match both "/" and "/link-1".
Related
I have a bottom navbar with icons. How can when the router-link has class 'active' it will turn into an active icon? Default icon 1 is active.
<li>
<router-link v-if="active" :class="{active}" active-class="active">
Icon 1 active
</router-link>
<router-link v-if="!active" :class="{active}" active-class="active">
Icon 1
</router-link>
</li>
<li>
<router-link v-if="active" :class="{active}" active-class="active">
Icon 2 active
</router-link>
<router-link v-if="!active" :class="{active}" active-class="active">
Icon 2
</router-link>
</li>
<li>
<router-link v-if="active" :class="{active}" active-class="active">
Icon 3 active
</router-link>
<router-link v-if="!active" :class="{active}" active-class="active">
Icon 3
</router-link>
</li>
The solution:
Binding the HTML class:
<li>
<router-link #click="isActive1 = true" :class="{ active: isActive1 }">
Icon 1
</router-link>
</li>
<li>
<router-link #click="isActive2 = true" :class="{ active: isActive2 }">
Icon 2
</router-link>
</li>
<li>
<router-link #click="isActive3 = true" :class="{ active: isActive3 }">
Icon 3 Active
</router-link>
</li>
Implement isActive variables:
data: {
isActive1: true, // default icon1
isActive2: false,
isActive3: false,
}
And implement watchers:
watch: {
isActive1(val) {
if(val === true) {
this.isActive2 = false
this.isActive3 = false
}
},
isActive2(val) {
if(val === true) {
this.isActive1 = false
this.isActive3 = false
}
},
isActive3(val) {
if(val === true) {
this.isActive1 = false
this.isActive2 = false
}
}
}
Documentation: https://v2.vuejs.org/v2/guide/class-and-style.html
I am new to Vue and straggling with generating sidebar list where each list element on click open its components. I am using vue router. I understand the theory how it should work, but obviously I am missing something because I can't solve it. I don't know how to dynamically change the path.
I generated sidebar list using router-link
<template>
<div class="sidebarListItems">
<router-link href="#"
:to="calcRut"
class="list-group-item list-group-item-action bg-light"
v-for="title in mapTitles"
:key="title.map"
:title="title.map"
#click="callMap">
{{title.map}}
</router-link>
</div>
</template>
<script>
import bus from "./js/bus"
import mapNames from "./json/popis_karata.json"
export default {
name: "PageSidebarList",
props: ["title"],
data(){
return {
mapTitles:mapNames,
ruth=""
}
},
methods: {
callMap(event){
bus.$emit("openMap")
},
calcRuth(){
for (var i=0; i<this.routes.length; i++){
var newruth = this.routes[i].path
this.ruth = newruth
}
}
},
computed: {
routes(){
return this.$router.options.routes
}
}
When I put my path directly as a string (:to="/zup" or :to="/reg") it's working, but I would like that those paths are dynamically generated depending on which list element I clicked.
Here's how I do it. Try extracting the v-for on the level above. If you don't want to use an actual element, try <template>
<ul class="flex flex-col w-full space-y-1">
<li v-for="item in items" :key="item.link">
<router-link class="flex items-center h-8 px-4 rounded-lg hover:bg-white" :class="{ 'bg-white': routeMatches(item) }" :to="{ name: item.link }">
<div class="text-sm text-gray-700">{{ item.name }}</div>
</router-link>
</li>
</ul>
Edit, also format your to="" correctly to be :to="{name: 'namehere'}"
how about this solution with a switch and a programmatic router change
<template>
<div id="app">
<ul class="nav">
<li class="nav-item" #click="routeChanger('home')">Home</li>
<li class="nav-item" #click="routeChanger('page1')">Page1</li>
<li class="nav-item" #click="routeChanger('page2')">Page2</li>
<li class="nav-item" #click="routeChanger('page3')">Page3</li>
<li class="nav-item" #click="routeChanger('page4')">Page4</li>
</ul>
</div>
</template>
<script>
export default {
name: "App",
methods: {
routeChanger(routeParam) {
switch (routeParam) {
case "home":
this.$router.push("/home");
break;
case "page1":
this.$router.push("/page1");
break;
//...
default:
this.$router.push("/404");
break;
}
}
}
};
</script>
<style>
</style>
Maybe my answer would be useful to someone so I am posting my solution.
I didn't found solution to loop separately navbar elements from one data file and router-lik :to path attribute from routes file.
It work if I use routes file for everything.
<router-link
v-for="route in $router.options.routes"
:key="route.path"
:to="route.path"
class="list-group-item list-group-item-action bg-light">
{{route.title}}
</router-link>
I am building a single page application using vue.js with materialize and I have a navbar with tabs to navigate to different pages on my website. Materialize's tabs has an active property that displays which tab is currently selected. Every thing this far works perfectly.
This is materialize's tabs reference
The Issue
If you refresh the web page the tabs active property 'resets' to its default position. So I am trying to figure out how to persist the state of the navbar's active property and then reassign it to router-link.
My Code
<ul id="tabs" class="tabs tabs-transparent" :class="{ 'navbar--color': !changeNavColor }">
<li class="tab" id="home">
<router-link
id="home"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="/"
>Home</router-link>
</li>
<li class="tab" id="services">
<router-link
id="services"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="Services"
>Service</router-link>
</li>
<li class="tab" id="Preapproved">
<router-link
id="Preapproved"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="PreApproved"
>Get Pre-Approved</router-link>
</li>
<li class="tab">
<router-link
id="cars"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="Cars"
>inventory</router-link>
</li>
<li class="tab">
<router-link
id="testimonials"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="Testimonials"
>Testimonals</router-link>
</li>
</ul>
if (localStorage.currentTab) {
this.currentTab = localStorage.currentTab;
var activeTab = document.getElementById(this.currentTab);
activeTab.classList.add("active");
console.log("saved");
}
$(document).ready(function() {
$("a").click(function(event) {
this.currentTab = event.target.id;
console.log(this.currentTab);
});
});
$(document).ready(function() {
$(".tabs").tabs();
});
window.addEventListener("scroll", this.onScroll);
},
beforeDestroy() {
window.removeEventListener("scroll", this.onScroll);
},
watch: {
currentTab(newTab) {
console.log("watch");
localStorage.currentTab = this.currentTab;
}
}
any help is appreciated
So I think you can use hash mechanism by using window.location.hash. You can put the data-toggle attribute in every tag anchor. And just check for location.hash !== ''
But the more Vue way would be through client side storage. Check the link its from vue docs. Although it is for the input field but you will get the idea of how to persist info by keeping a reference in client storage and on reload getting your desired state from there onward. Hope it helps.
Remove the indicator that is nested inside the first li, and the navigation works fine.
<ul id="tabs" class="tabs tabs-transparent">
<li id="tab" class="tab">
Home
<li class="indicator"></li> <!-- THIS RANDOM NESTED INDICATOR IS THE ISSUE -->
</li>
<li id="tab" class="tab">
Service
</li>
<li id="tab" class="tab">
Get Pre-Approved
</li>
<li id="tab" class="tab">
inventory
</li>
<li class="indicator" style="right: 488px; left: 0px;"></li> <!-- CORRECT INDICATOR, AUTOMATICALLY GENERATED BY MATERIALIZE -->
</ul>
This is how I ended up implementing this. First all of your router-links or <a> have to have unique id's
mounted() {
if (localStorage.currentTab) {
this.currentTab = localStorage.currentTab;
var element = document.querySelector(this.currentTab);
element.classList.add("active");
}
$(document).ready(function() {
$(".tabs").tabs();
$("a").click(function(event) {
this.currentTab = "#" + event.target.id;
localStorage.currentTab = this.currentTab;
});
});
},
watch: {
currentTab(newTab) {
localStorage.currentTab = this.currentTab;
}
}
i want to toggle highlighting for the routerLinkActive based on the routes,
i have a dashboard component and both the dashboard menu item and labels menu item refer to the same component, i want to add class to the li items based on the route
for dashboard the route will be
http://localhost:4300/dashboard
and for the labels , the route will be
http://localhost:4300/dashboard/5d1bb53877ed8702d8a01940
Code for the menu item
<ul class="sidebar-nav">
<li [ngClass]="{ active: rlal && rlal.isActive == false }">
<a [routerLink]="['/dashboard']" (click)="loadSnippet(null)">
<mat-icon>dashboard</mat-icon>
<span>Dashboard</span>
</a>
</li>
<h3 *ngIf="labelList && labelList.length!=0">Labels</h3>
<ul class="sidebar-nav">
<li *ngFor="let label of labelList" [ngClass]="rlal && rlal.isActive ? 'active' : ''"
routerLinkActive="rlal.isActive">
<a [routerLink]="['/dashboard', label._id]" routerLinkActive #rlal="routerLinkActive"
(click)="loadSnippet(label)">
<mat-icon>label</mat-icon>
<span>{{ label.label_name }} </span>
</a>
</li>
</ul>
Routes:
{
path: "dashboard",
component: DashboardComponent,
canActivate: [LoggedInGuard]
},
{
path: "dashboard/:labelId",
component: DashboardComponent,
canActivate: [LoggedInGuard]
}
The highlighting works fine for the individual label items, but for the dashboard , the li is not getting highlighted
If you want the dashboard link to be active only if there's no route parameter, you need to add routerLinkActive and [routerLinkActiveOptions]="{exact: true}" to you dashboard li node.
Also, you don't need to set the active class via ngClass, because routerLinkActive will do that for you.
<li routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
<a routerLink="/dashboard" (click)="loadSnippet(null)">
<mat-icon>dashboard</mat-icon>
<span>Dashboard</span>
</a>
</li>
...
<li routerLinkActive="active" *ngFor="let label of labelList">
<a [routerLink]="['/dashboard', label._id]" (click)="loadSnippet(label)">
<mat-icon>label</mat-icon>
<span>{{ label.label_name }}</span>
</a>
</li>
Template:
<template name="header">
<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item {{active}}" href="{{pathFor 'homePage'}}">Home</a>
{{#if currentUser}}
<a class="blog-nav-item {{active}}" href="#">{{Meteor.userId}}</a>
{{else}}
<a class="blog-nav-item {{active}}" href="{{pathFor 'loginPage'}}">Login</a>
<a class="blog-nav-item {{active}}" href="{{pathFor 'signUpPage'}}">Sign Up</a>
{{/if}}
<a class="blog-nav-item {{active}}" href="#">About</a>
</nav>
</div>
</div>
</template>
header.js
Template.header.events({
'click a': function(e) {
e.preventDefault();
this.active?"active":"";
}
});
I just want to make set click link's class as active. Clicked link class should look like class="blog-nav-item active".
The example below relies on iron-router and presents a reactive approach for adding the active class
First should modify the template to be:
<a class="blog-nav-item {{active 'homePage'}}" href="{{pathFor 'homePage'}}">Home</a>
And then the appropriate helper for it should be:
Template.name.helpers({
active: function(routeName) {
var curRoute = Router.current().route;
return curRoute.name === routeName ? 'active' : '';
}
});
Edit v1.0+
As of iron-router 1.0, A route's name is now accessible at
route.getName() (previously it was route.name).
In particular, you'll need to write return
curRoute.getName() === routeName ? 'active' : '';
Thank you #jrbedard for the notification
I guess this would be the "Meteor way" you wanted:
<template name="menu">
<ul>
<li class="{{#if isCurrentPage 'pageA'}}active{{/if}}">
Page A
</li>
<li class="{{#if isCurrentPage 'pageB'}}active{{/if}}">
Page B
</li>
<li class="{{#if isCurrentPage 'pageC'}}active{{/if}}">
Page C
</li>
</ul>
</template>
Router.onBeforeAction(function(){
Session.set('currentRouteName', Router.current().route.name)
})
Template.menu.helpers({
isCurrentPage: function(pageName){
return Session.equals('currentRouteName', pageName)
}
})
Router.current().route.name do evaluate to the current page name in the latest version of iron router, but I don't know if that's part of the public API one should use.
EDIT
Router.current() is apparently reactive, so all JavaScript code you need is the following:
Template.menu.helpers({
isCurrentPage: function(pageName){
return Router.current().route.name == pageName
}
})
You can solve it with JavaScript only:
Template.header.events({
'click .blog-nav-item': function(event, template){
// Remove the class 'active' from potentially current active link.
var activeLink = template.find('.blog-nav-item')
if(activeLink){
activeLink.classList.remove('active')
}
// Add the class 'active' to the clicked link.
event.currentTarget.classList.add('active')
}
})