Vue.js 更改键后不响应鼠标事件



我刚刚在 Vue 中发现了奇怪的行为。更改组件的键后,我的自定义鼠标事件绑定不再起作用。我知道我们不应该将jQuery与Vue混合使用,但这只是一个测试。我不明白为什么会这样。对此有何解释?它与虚拟DOM有关吗?我更多地寻求解释为什么会发生这种情况,而不是寻求解决方案。

我注意到当我检查 DOM 时,一切看起来都正确。但是鼠标事件不起作用。

这是它的工作原理。

1. When you click on the two green buttons it should print out the data-key attribute for that button.
2. Then click on the "Change keys" button and the keys for components will change
3. Now click again on the green buttons but they will no longer print their data-key attributes to the screen.
<div id="app">
  <button @click="key1+=5; key2++">Change keys</button>
  <my-button :data-key="key1" :key="key1"></my-button>
  <my-button :data-key="key2" :key="key2"></my-button>
  <div id="console"></div>
</div>
Vue.component('my-button', {
  data() {
    return {
      count: 0
    }
  },
  template: `<button
                class="btn"
                style="background: lightgreen"
                @click="count++">
                You clicked me {{ count }} times.
             </button>`
})
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!',
    key1: 1,
    key2: 2,
  },
  mounted()
  {
    $('.btn').mousedown(function(event) {
      $('#console').append(
        'data-key: ' +
        event.target.getAttribute('data-key') +
        '<br>'
      )
    })
  }          
})

这是一个工作小提琴:https://jsfiddle.net/queeeeenz/zuye12oL/18/

更改键时,会重新渲染元素。您的事件绑定在初始按钮上。新的没有附加任何事件。

如果要绑定应用中的所有当前和将来按钮,则必须绑定到不会消失的元素,语法略有不同:

$('#app').on('mousedown', '.btn', function(event) {
  $('#console').append(
    'data-key: ' +
    event.target.getAttribute('data-key') +
    '<br>'
  )
})

在这里看到它。

工作理由:使用直接绑定语法(您的情况(,选择器在绑定时进行评估。对于第二个(委托事件(,将在事件发生时根据事件的目标对其进行评估。

阅读 jquery 的 on(( 页面上"委托事件"部分下的完整说明。

最新更新