美文网首页
v-for循环出来的元素,实现鼠标放在当前元素,改变样式

v-for循环出来的元素,实现鼠标放在当前元素,改变样式

作者: Vincent1223 | 来源:发表于2020-05-21 00:09 被阅读0次

有时候会遇到这种需求,一个列表,鼠标放上去,滑到哪里,哪个元素就变色,如果列表是v-for循环出来的,该如何实现这种效果呢?
看案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .red {
            color: red;
            background-color: orange;
        }
    </style>
</head>
<body>
<div id="app">
    <h2>{{message}}</h2>
    <ul>
        <li v-for="(item,index) in movies" @mouseover = 'over(index)' :class="{red:index==mainIndex}">{{item}}</li>
    </ul>
</div>
<script src="vue.js"></script>
<script>
  const v =  new Vue({
        el:"#app",
        data:{
            message:'你好啊',
            movies:['星际穿越','侠影之谜','黑暗骑士','盗梦空间','信条','指环王'],
            isRed:false,
            mainIndex:-1
        },
        methods:{
            over:function(index){
                this.mainIndex = index;

            }
        }
      }
    )
</script>

</body>

其中使用了v-for遍历和v-bind绑定class样式,注意因为是改变单一元素的样式,所以需要获取对象元素的index,把index赋值到data中的变量mainIndex,在v-bind中通过判断当前元素的index是否等于mainIndex来作为添加样式条件。
效果如下:

鼠标未滑过时:
鼠标滑过时:

相关文章

网友评论

      本文标题:v-for循环出来的元素,实现鼠标放在当前元素,改变样式

      本文链接:https://www.haomeiwen.com/subject/tqkaohtx.html