Vue.js メニュー上でカレントページを強調するクラスを付与する

現在のページのパス(URL)を条件にクラスを付与するような条件を書けばいい。

bootstrap vueで言うとこんな感じ。

<b-navbar toggleable="lg" type="dark" variant="dark">
    <b-navbar-brand href="#">NavBar</b-navbar-brand>
    <b-navbar-toggle target="nav-collapse"></b-navbar-toggle>
    <b-collapse id="nav-collapse" is-nav>
        <b-navbar-nav>
            <b-nav-item :class="{'active': $route.path === '/'}" to="/">Home</b-nav-item>
            <b-nav-item :class="{'active': $route.path === '/about'}" to="/about">About</b-nav-item>
            <b-nav-item :class="{'active': $route.path === '/stocks/create'}" to="/stocks/create">Post
            </b-nav-item>
            <b-nav-item :class="{'active': $route.path === '/stocks'}" to="/stocks">Archive</b-nav-item>
            <b-nav-item :class="{'active': $route.path === '/login'}" to="/login">Login</b-nav-item>
            <b-nav-item :class="{'active': $route.path === '/register'}" to="/register">Register
            </b-nav-item>
        </b-navbar-nav>
        <!-- Right aligned nav items -->
        <b-navbar-nav class="ml-auto">
            <b-nav-form>
                <b-form-input size="sm" class="mr-sm-2" placeholder="Search"></b-form-input>
                <b-button size="sm" class="my-2 my-sm-0" type="submit">Search</b-button>
            </b-nav-form>
            <b-nav-item-dropdown right v-if="isLoggedIn">
                <!-- Using 'button-content' slot -->
                <template #button-content>
                    <em>{{ userName }}</em>
                </template>
                <b-dropdown-item href="#">Profile</b-dropdown-item>
                <b-dropdown-item href="#">Sign Out</b-dropdown-item>
            </b-nav-item-dropdown>
            <button v-if="!(userName)">ログイン</button>
        </b-navbar-nav>
    </b-collapse>
</b-navbar>

:class="{'active': $route.path === '/ページのパス'}"

が重要。

active はクラス名で、他とは異なる色などをCSS側で当てればいい。

 

参考文献

vue-router 現在のパスによってスタイルを変更する

 

 

無制限に質問可能なプログラミングスクール!

万が一転職できない場合は、転職保障全額返金できるコースもあり!!

無制限のメンター質問対応

 

DMMウェブキャンプでプログラミングを学習しませんか?

独学より成長スピードをブーストさせましょう!

 

まずは無料相談から!

おすすめの記事