Vue学习:5.v-bind使用

第一节算是对v-bind的粗略了解,仅仅是列举了v-bind的使用。这一节将更详细的了解v-bind的具体用法。

v-bind是 Vue.js 中常用的指令之一,用于动态地绑定属性或者表达式到 HTML 元素上。通过 v-bind,你可以将 Vue 实例的数据绑定到元素的属性上,实现数据的动态更新。

v-bind实例:tab导航高亮

实现功能:

点击tab栏不同导航时,点击对象高亮显示。

思路:

当使用导航栏时,通常会使用一个包含超链接的列表,通过设置 v-bind 来动态绑定激活高亮类属性。

代码:

html:

<div id="app"> 
        <ul>
            //基于vue实例数据,使用v-for动态渲染列表
            //key 是用来标识 Vue 中的每个节点的特殊属性
            //:key="item.id"的作用是为每个列表项指定一个唯一的标识符,
            //以确保在列表数据变化时,Vue 能够正确地识别每个节点,并进行高效的更新
            //定义点击事件:当事件初发时,激活点击项的active类
            <li v-for="(item,index) in  list" :key="item.id" @click="activeIndex = index">
                <a :class="{active: index === activeIndex}" href="#">{{ item.name }}</a>
            </li>
        </ul>
</div>

js:

<script>
        const app = new Vue({
            el: '#app',
            data: {
                activeIndex: 0,
                list: [
                    {id: 1, name: '桃保直播'},
                    {id: 2, name: '限时秒杀'},
                    {id: 3, name: '百亿补贴'}
                ]
            }
        })
</script>

css:

<style>
        #app{
            height: 50px;
            margin-left: 10px;
        }
        ul{
            list-style: none;
        }
        li{
            width: 100px;
            height: 50px;
            line-height: 50px;
            float: left;
        }
        a{
            text-decoration: none;
            color: black;
        }
        //定义active类
        .active{
            height: 50px;
            width: 90px;
            color: white;
            background-color: red;
        }
 </style>

posted @ 2024-04-08 18:43  Fly宇航员  阅读(79)  评论(0)    收藏  举报  来源