vue實現tab選項卡


效果圖:

主要思路:

  • 點擊不同 tab 獲取 tab 選項卡下標並為其動態綁定一個class(選中狀態時的樣式)

  • 點擊時使 tab 對應的內容下標與 tab 選項卡下標保持一致

  • 使用 v-show / v-if 指令控制內容顯示與隱藏

源碼:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>tab選項卡</title>
    <script src="js/vue.js"></script>
    <style>
        ul,
        li {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        #app {
            width: 600px;
            height: 400px;
            margin: 0 auto;
            border: 1px solid #ccc;
        }

        .tab-tilte {
            width: 100%;
        }

        .tab-tilte li {
            float: left;
            width: 25%;
            padding: 10px 0;
            text-align: center;
            background-color: #f4f4f4;
            cursor: pointer;
        }

        /* 點擊對應的標題添加對應的背景顏色 */
        .tab-tilte .active {
            background-color: #09f;
            color: #fff;
        }

        .tab-content div {
            float: left;
            width: 25%;
            line-height: 100px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="app">
        <ul class="tab-tilte">
            <!-- 方法一: class對象-->
            <!-- <li v-for="(title,index) in tabTitle" @click="cur=index" :class="{active:cur==index}">{{title}}</li> -->

            <!-- 方法二: class數組+三元運算-->
            <li v-for="(title,index) in tabTitle" @click="check(index)" :class="[cur == index ? 'active' : '']">{{title}}
            </li>
        </ul>
        <div class="tab-content">
            <div v-for="(m,index) in tabMain" v-show="cur==index">{{m}}</div>
        </div>
    </div>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                tabTitle: ['標題一', '標題二', '標題三', '標題四'],
                tabMain: ['內容一', '內容二', '內容三', '內容四'],
                cur: 0 //默認選中第一個tab
            },
            methods: {
                check: function (index) {
                    this.cur = index
                }
            },
        })
    </script>

</body>

</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM