javascript 在鼠标悬停时动态添加和删除类 - Vue.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48892189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:19:50  来源:igfitidea点击:

Dynamically add and remove classes on mouseover - Vue.js

javascriptvue.jsvue-component

提问by Bitwise

I can successfully add a class on mouseover with Vue. But I want to remove the class when the mouse leaves the element. What is the idiomatic way of handling this in Vue?

我可以使用 Vue 在鼠标悬停时成功添加一个类。但是我想在鼠标离开元素时删除该类。在 Vue 中处理这个的惯用方法是什么?

<template>
  <div id="navigation">
    <div class="nav-container">
      <nav>
        <router-link to="/" class="home">Ping Party</router-link>
        <div class="navigation-actions">
          <router-link to="/sign_in" v-if="!isLoggedIn" class="sign_in">Sign In</router-link>
          <router-link to="/sign_up" v-if="!isLoggedIn" @mouseover.native="mouseOver" class="sign_up" ref="sign_up">Sign Up</router-link>
          <router-link to="/users" v-if="isLoggedIn" class="users">Users</router-link>
          <v-btn :click.prevent="signOut()" v-if="isLoggedIn">Sign Out</v-btn>
        </div>
      </nav>
    </div>
  </div>
</template>

<script>
  import SignUp from "../forms/SignUp";
  import SignIn from "../forms/SignIn";

  export default {
    components: {
      SignUp,
      SignIn
    },
    computed: {
      isLoggedIn () {
        return this.$store.getters.isLoggedIn
      }
    },
    methods: {
      signOut: function() {
        this.$store.commit("LOGOUT")
        this.$store.commit("FLASH_MESSAGE", {
          message: "Signed Out Successfully",
          show: true,
          styleClass: "error",
          timeOut: 4000
        })
        this.$router.push('/')
      },
      mouseOver: function() {
        this.$refs.sign_up.$vnode.elm.classList.add("hovered")
      }
    }
  }
</script>

As you can see on mouseover I call the mouseOver function and this successfully adds the class to the element. But now when the users leaves the element the class remains. How can I have the class remove when the user leaves the element? Thanks for the help.

正如你在 mouseover 上看到的,我调用了 mouseOver 函数,这成功地将类添加到元素中。但是现在当用户离开元素时,类仍然存在。当用户离开元素时,如何删除类?谢谢您的帮助。

回答by Bert

Listen for both mouseoverand mouseoutand set the class based on that.

听两者mouseovermouseout根据它设置类。

console.clear()

new Vue({
  el: "#app",
  data:{
    isHovering: false
  }
})
.hovering{
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <h1 @mouseover="isHovering = true" 
      @mouseout="isHovering = false" 
      :class="{hovering: isHovering}">
    {{ isHovering ? "Woot! Hovered" : "Hover over me" }}
  </h1>
</div>

Or just use CSS.

或者只是使用 CSS。

console.clear()

new Vue({
  el: "#app",
  data:{
    isHovering: false
  }
})
h1:hover{
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <h1 @mouseover="isHovering = true" 
      @mouseout="isHovering = false" >
    {{ isHovering ? "Woot! Hovered" : "Hover over me" }}
  </h1>
</div>

回答by Achilles Moraites

A more scalable solution would be to use a directive:

更具可扩展性的解决方案是使用指令:

// Directives
Vue.directive('add-class-hover', {
  bind(el, binding, vnode) {    
    const { value="" } = binding;
    el.addEventListener('mouseenter',()=> {
        el.classList.add(value)
    });
    el.addEventListener('mouseleave',()=> {
        el.classList.remove(value)
    });
  },
  unbind(el, binding, vnode) {
    el.removeEventListener('mouseenter');
    el.removeEventListener('mouseleave')
  }
})

new Vue({
  el: "#app"
})
.hoverClass {
color: red;
font-weight: 700;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h1 v-add-class-hover="'hoverClass'">
    Text
  </h1>
</div>