我刚刚在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/
答案 0 :(得分:1)
更改键时,将重新渲染元素。并且您的事件绑定在初始按钮上。新事件没有附加事件。
如果要绑定应用程序中所有当前和将来的按钮,则必须绑定到不会消失的元素,语法略有不同:
$('#app').on('mousedown', '.btn', function(event) {
$('#console').append(
'data-key: ' +
event.target.getAttribute('data-key') +
'<br>'
)
})
here看到它。
工作原理:使用直接绑定语法(根据您的情况),选择器在绑定时进行评估。对于第二个事件(委派事件),它会在事件发生时根据事件的目标进行评估。
在jquery的on()页的“委派事件”部分下阅读完整说明。