I want my sidebar dropdown to be available only one at a time, so when I click on another dropdown, the previous dropdown will be hidden again.
Below is the example of my current dropdown, which where you can open multiple dropdowns at a time. https://coreui.io/vue/demo/#/dashboard
<template>
<router-link tag="li" class="nav-item nav-dropdown" :to="url" disabled>
<div class="nav-link nav-dropdown-toggle" @click="handleClick"><i :class="icon"></i> {{name}}</div>
<ul class="nav-dropdown-items">
<slot></slot>
</ul>
</router-link>
</template>
<script>
export default {
props: {
name: {
type: String,
default: ''
},
url: {
type: String,
default: ''
},
icon: {
type: String,
default: ''
}
},
methods: {
handleClick(e) {
e.preventDefault();
e.target.parentElement.classList.toggle('open');
}
}
};
</script>
Please help.
The usual way to make a radio-group type controller (where only one item can be selected at once) is to have a variable that indicates which one is selected. Then each element compares itself to the selected one to determine whether it should be in the open state.
Since you have multiple router-link
s that don't know about each other, the parent object is going to have to own the which-one-is-selected indicator variable. The handleClick
of your router-link
should $emit
an event that the parent will handle by changing the indicator variable. And the router-link
should receive the indicator variable as a prop and use it in a computed to set the open
class as appropriate.
Your code might look like this:
<template>
<router-link tag="li" class="nav-item nav-dropdown" :class="openClass" :to="url" disabled>
<div class="nav-link nav-dropdown-toggle" @click="handleClick"><i :class="icon"></i> {{name}}</div>
<ul class="nav-dropdown-items">
<slot></slot>
</ul>
</router-link>
</template>
<script>
export default {
props: {
name: {
type: String,
default: '',
selectedItem: Object
},
url: {
type: String,
default: ''
},
icon: {
type: String,
default: ''
}
},
computed: {
openClass() {
return this.selectedItem === this ? 'open' : '';
}
}
methods: {
handleClick(e) {
e.preventDefault();
this.$emit('setSelected', this);
}
}
};
</script>