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>
posted @ 2021-03-27 12:38  星河几重  阅读(3714)  评论(0编辑  收藏  举报