Vue中动态Class实战

简介: Vue中动态Class实战

效果展示

需求

想实现一个假如有5个div块,默认都是灰色,鼠标悬浮到哪个div上,那个div就显示为黑色。

具体的实现业务逻辑可根据这个进行演变

设计

通过动态 class 类名来实现,实现鼠标悬浮到div时动态绑定class

版本

  • Vue 3.3.4
  • Node 20.9.0

代码

<template>  
    <div class="container">  
      <div v-for="(box, index) in boxes" :key="index"  :class="'box'+ index"
      :style="{ color: box.color, backgroundColor: box.backgroundColor }">  
        {{ box.content }}  
      </div>  
    </div>  
  </template>  
    
  <script>  
  export default {  
    data() {  
      return {  
        boxes: [  
          { content: 'Box 1', color: 'white', backgroundColor: 'grey' },  
          { content: 'Box 2', color: 'white', backgroundColor: 'grey' },  
          { content: 'Box 3', color: 'white', backgroundColor: 'grey' },  
          { content: 'Box 4', color: 'white', backgroundColor: 'grey' },  
          { content: 'Box 5', color: 'white', backgroundColor: 'grey' }  
        ]  
      };  
    },  
    methods: {  
      handleMouseOver(index) {  
        console.log('鼠标移入:',index)
        this.boxes[index].backgroundColor = 'black';  
        this.boxes[index].color = 'white';  
      },  
      handleMouseOut(index) {  
        console.log('鼠标移出:',index)
        this.boxes[index].backgroundColor = 'grey';  
        this.boxes[index].color = 'white';  
      }  
    },  
    mounted() {  
      this.boxes.forEach((box, index) => {  
        console.log("页面初始化:",box,index)
        this.$el.querySelector('.box'+index).addEventListener('mouseover', () => this.handleMouseOver(index));  
        this.$el.querySelector('.box'+index).addEventListener('mouseout', () => this.handleMouseOut(index));  
      });  
    }  
  };  
  </script>
目录
相关文章
|
1天前
|
JavaScript
Vue实战-组件通信
Vue实战-组件通信
4 0
|
1天前
|
JavaScript
Vue实战-将通用组件注册为全局组件
Vue实战-将通用组件注册为全局组件
5 0
|
1天前
|
JavaScript 前端开发
vue的论坛管理模块-文章评论02
vue的论坛管理模块-文章评论02
|
1天前
|
JavaScript Java
vue的论坛管理模块-文章查看-01
vue的论坛管理模块-文章查看-01
|
1天前
|
JavaScript
vue页面加载时同时请求两个接口
vue页面加载时同时请求两个接口
|
1天前
|
JavaScript
vue里样式不起作用的方法,可以通过deep穿透的方式
vue里样式不起作用的方法,可以通过deep穿透的方式
|
JavaScript 前端开发
Vue入门---属性、style和class绑定方法
一 、用对象的方法绑定class 1 DOCTYPE html> 2 3 4 5 class与style绑定 6 7 8 9 .
1328 0
|
1天前
|
移动开发 JavaScript 应用服务中间件
vue打包部署问题
Vue项目`vue.config.js`中,`publicPath`设定为&quot;/h5/party/pc/&quot;,在线环境基于打包后的`dist`目录,而非Linux的`/root`。Nginx代理配置位于`/usr/local/nginx/nginx-1.13.7/conf`,包含两个相关配置图。
vue打包部署问题
|
1天前
|
JavaScript 前端开发
iconfont 图标在vue里的使用
iconfont 图标在vue里的使用
11 0
|
1天前
|
资源调度 JavaScript 前端开发
vue 项目运行过程中出现错误的问题解决
vue 项目运行过程中出现错误的问题解决