4

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>
0

1 Answer 1

8

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"
});
Sign up to request clarification or add additional context in comments.

2 Comments

You solution does work when I just click the link. But it doesn't work for refresh in submenu. I use admin-lite template for the left sidebar. Would you give me the solution for that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.