Vue实现Tab栏切换(v-for渲染)

在用数据渲染前端页面的几种方式下,原生js和jQuery都需要操作DOM,生成元素,添加元素等一系列操作,而Vue只需要v-for指令就轻松解决。

实现功能:有标题和图片两部分组成,点击相应的标题显示响应的图片,其他图片隐藏。

实现效果:
在这里插入图片描述
在这里插入图片描述
代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="js/Vue.js"></script>
    <style>
        .tab {
            width: 400px;
            height: 300px;
            border: 1px solid #ccc;
            margin: 50px auto;
        }
        ul {
            margin: 0;
            padding: 0;
            height: 50px;
        }
        li {
            cursor: pointer;
            box-sizing: border-box;
            height: 50px;
            width: 100px;
            list-style: none;
            text-align: center;
            line-height: 50px;
            float: left;
            border-right:1px solid #ccc;
            border-bottom: 1px solid #ccc;
        }
        .active {
            background-color: pink;
        }
        .img {
            display: none;
            height: 250px;
            width: 400px;
        }
        .img img {
            height: 100%;
            width: 100%;
        }
        .current {
            display: block;
        }
    </style>
</head>
<body>
    <div class="tab" id="tab">
        <ul>
            <li @click='change(index)' :class='currentIndex==index?"active":""' :key='item.id' v-for='(item,index) in list'>{{item.title}}</li>
            
        </ul>
        <div :class='currentIndex==index?"current":""' class="img" :key='item.id' v-for='(item,index) in list'>
            <img :src="item.path" alt="">
        </div>
    </div>
    <script>
        var vm=new Vue({
            el:'.tab',
            data:{
                currentIndex:0,
                list:[{
                id:1,
                title:'武则天',
                path:"img/武则天.jpg",
            },
            {
                id:2,
                title:'李白',
                path:"img/李白.jpg",
            },
            {
                id:3,
                title:'伽罗',
                path:"img/伽罗.jpg",
            },
            {
                id:4,
                title:'大乔',
                path:"img/大乔.jpg",
            }]
            },
            methods:{
                change:function(index){
                    this.currentIndex=index;
                }
            }
        });
    </script>
</body>
</html>

Vue实现了另一种方式的编程,可以快速的将后端传的数据渲染到页面。

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