使用Vue.js寫一個簡單的導航菜單

使用Vue.js寫一個簡單的導航菜單

代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
</head>
<style>

    *{
        margin:0;
        padding:0;
    }

    body{
        font:15px/1.3 'Open Sans', sans-serif;
        color: #5e5b64;
        text-align:center;
    }

    a, a:visited {
        outline:none;
        color:#389dc1;
    }

    a:hover{
        text-decoration:none;
    }

    section, footer, header, aside, nav{
        display: block;
    }

    /*-------------------------
        菜鳥
    --------------------------*/

    nav{
        display:inline-block;
        margin:60px auto 45px;
        background-color:#5597b4;
        box-shadow:0 1px 1px #ccc;
        border-radius:2px;
    }

    nav a{
        display:inline-block;
        padding: 18px 30px;
        color:#fff !important;
        font-weight:bold;
        font-size:16px;
        text-decoration:none !important;
        line-height:1;
        text-transform: uppercase;
        background-color:transparent;

        -webkit-transition:background-color 0.25s;
        -moz-transition:background-color 0.25s;
        transition:background-color 0.25s;
    }

    nav a:first-child{
        border-radius:2px 0 0 2px;
    }

    nav a:last-child{
        border-radius:0 2px 2px 0;
    }

    nav.home .home,
    nav.best .best,
    nav.animal .animal,
    nav.hello .hello{
        background-color:#e35885;
    }

    p{
        font-size:22px;
        font-weight:bold;
        color:#7d9098;
    }

    p b{
        color:#ffffff;
        display:inline-block;
        padding:5px 10px;
        background-color:#c4d7e0;
        border-radius:2px;
        text-transform:uppercase;
        font-size:18px;
    }

</style>
<body>
<div id="main">
    <!-- 菜單樣式爲active類 -->
    <nav v-bind:class="active" v-on:click.prevent>
        <!-- 當菜單鏈接被點擊,調用makeActive方法 -->
        <a href="#" class="home" v-on:click="makeActive('home')">home</a>
        <a href="#" class="best" v-on:click="makeActive('best')">best</a>
        <a href="#" class="animal" v-on:click="makeActive('animal')">animal</a>
        <a href="#" class="hello" v-on:click="makeActive('hello')">hello</a>
    </nav>
    <p>選擇了<b>{{active}}</b>菜單</p>
</div>
<script>
    //創建新的Vue實例
    var vm = new Vue({
        //DOM元素,掛載視圖模式
        el:'#main',
        //定義屬性,設置初始值
        data:{
          active:'home'
        },
        //點擊菜單使用的函數
        methods:{
            makeActive:function(item){
                //模式改變,視圖會自動更新
                this.active=item;
            }
        }
    })
</script>
</body>
</html>

運行界面

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章