【问题标题】:VueJS parent mouseover event masking child mouseover eventVueJS父鼠标悬停事件屏蔽子鼠标悬停事件
【发布时间】:2018-08-13 14:19:57
【问题描述】:

我正在使用 VueJS 并尝试在两个元素上触发鼠标悬停事件,一个是另一个的子元素。

我无法触发子鼠标悬停事件。似乎父元素正在“覆盖”子 div,并且仅注册了父鼠标悬停事件。

var vm = new Vue({
  el: '#app',
  data: {
    hoverTarget: 'none'
  },
  methods: {
    parentHover: function() {
      this.hoverTarget = 'parent'
    },
    childHover: function() {
      this.hoverTarget = 'child'
    }
  }
});
#parent {
  width: 100px;
  height: 100px;
  background: #000000;
}

#child {
  width: 50px;
  height: 50px;
  background: #FFFFFF;
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
<div id='app'>
  <div id='parent' @mouseover="parentHover">
    <div id='child' @mouseover="childHover">

    </div>
  </div>
  {{ hoverTarget }}
</div>

【问题讨论】:

    标签: javascript html css vue.js event-handling


    【解决方案1】:

    此外,您可以使用event modifier 将其缩写为@mouseover.stop="childHover"

    【讨论】:

      【解决方案2】:
       <div id='app'>
        <div id='parent' @mouseover="parentHover">
          <div id='child' @mouseover="childHover">
      
          </div>
        </div>
        {{ hoverTarget }}
      </div>
      

      发生这种情况是因为 事件冒泡 原则

      当一个事件发生在一个元素上时,它首先运行它的处理程序, 然后是它的父代,然后一直到其他祖先。

      这意味着childHover 处理程序将在它之后立即执行 parentHover 将被执行,使子执行不可见。

      要解决您的问题,您可以使用事件的event.stopPropagation() 方法来确保从子到父不会发生冒泡。

      var vm = new Vue({
        el: '#app',
        data: {
          hoverTarget: 'none'
        },
        methods: {
          parentHover: function() {
            this.hoverTarget = 'parent'
          },
          childHover: function(event) {
            event.stopPropagation()
            this.hoverTarget = 'child'
          }
        }
      });
      

      【讨论】:

      • 如果我删除 'event' 函数参数,这将起作用。谢谢!
      • 这个想法是停止事件传播。每个事件处理程序都会让您访问被触发的事件。你只需要停止传播
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2016-08-08
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多