Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set active menu option with Vue

I have a two column layout. The left column has a stacked menu, and when the user selects an option the content displays in the right. What's the best way to set the active class on the selected menu link?

I have come up with a solution below, but it seems kind of verbose. Each menu item has a class assignment which is conditional upon data.activeTab. A click event handler updates the value of data.activeTab.

<template>
    <div>
        <div class="row">
            <div class="col-md-3">
                <ul class="nav nav-pills nav-stacked">
                    <li role="presentation" :class="{active : activeTab == 'option1'}">
                        <a :href="'/#/sales/' + uuid + '/option1'" @click="updateMenu">Option 1</a>
                    </li>
                    <li role="presentation" :class="{active : activeTab == 'option2'}">
                        <a :href="'/#/sales/' + uuid + '/option2'" @click="updateMenu">Option 2</a>
                    </li>
                </ul> 
            </div>
            <div class="col-md-9">
                <router-view></router-view>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data : function () {
            return {
                activeTab : 'option1'
            }
        },
        props : [
            'uuid'
        ],
        methods : {
            updateMenu : function (event) {
                var str = event.target.toString();
                this.activeTab = str.substr(str.lastIndexOf('/') + 1);
            }
        }
    }
</script>
like image 784
DatsunBing Avatar asked Mar 10 '23 11:03

DatsunBing


1 Answers

Use router-link instead of your manual anchor tags and set the linkActiveClass in your router construction options.

I can't see your routes object, so this is a best guess based on what you have above. Refer to the router link documentation I linked above to determine the best way to set up your to attributes.

<router-link tag="li" :to="{ path: 'sales', params: { uuid : uuid, option: "option1" }}">
    <a>Option 1</a>
</router-link>
<router-link tag="li" :to="{ path: 'sales', params: { uuid : uuid, option: "option2" }}>
    <a>Option 2</a>
</router-link>

Then, wherever you initialized your router,

new VueRouter({
    routes,
    linkActiveClass: "active"
});
like image 63
Bert Avatar answered Mar 12 '23 02:03

Bert