1

I am using this code :

   <router-link
                    v-for="item in navigation"
                    :key="item.name"
                    :to="item.to"
                    @click="(item.current = true) "
                    :class="[
                      item.current
                        ? 'bg-gray-900 text-white'
                        : 'text-gray-300 hover:bg-gray-700 hover:text-white',
                      'group flex items-center px-2 py-2 text-base font-medium rounded-md',
                    ]"
                  >

 const navigation = [
    { name: "Dashboard", to: "/", icon: HomeIcon, current: false },
    { name: "About", to: "/about", icon: UsersIcon, current: false },
    { name: "Projects", to: "about", icon: FolderIcon, current: false },
  ];`

My question is how can i make this work with routerlink? I want to have the current item change to true when you select it. SO that the tailwind class changes. I tried (item.current = true) but this changes all the current objects to true. The code you see is from tailwind components sidebar example. https://tailwindui.com/components/application-ui/application-shells/sidebar

I now use active-class and that works somehow. But still want to know how to do it probably.

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164

2 Answers2

0

Create a reactive property called selectedItemName that you can update by assigning the clicked item to it :

import {ref} from 'vue'

 const selectedItemName = ref('')

in template assign the selected item name to selectedItemName then use in the conditional class:

 <router-link
                    v-for="item in navigation"
                    :key="item.name"
                    :to="item.to"
                    @click="()=>selectedItemName=item.name"
                    :class="[
                      item.name === currentItem
                        ? 'bg-gray-900 text-white'
                        : 'text-gray-300 hover:bg-gray-700 hover:text-white',
                      'group flex items-center px-2 py-2 text-base font-medium rounded-md',
                    ]"
                  >
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
0

The answer of Boussadjra Brahim works.

Just wanted to add: The reason for all current objects = true is that you do not change them back to false, when you click on an other item. So if you do not want to use a separate object for storing the current information, you could call a function that turns all the [item].currents to false. Then proceed like you do now.

Niro
  • 142
  • 9
  • This is an interesting point. But this case is only possible if he first clicks on all items once and forgets to set them false again. As OP didn't mention so not sure this could be the reason. :-D – Neha Soni Feb 23 '23 at 05:34
  • True, I tried to reproduce the described behavior but it worked as expected. The items not turning to false seemed the most likely scenario. – Niro Feb 23 '23 at 10:18