我正在尝试从组件的子组件中监听鼠标事件,但我没有触发该事件。当我在 html 中监听事件时它起作用,但不是
如您所见,这是有效的:
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#mouse',
data: {
message: 'Hover Me!'
},
methods: {
mouseover: function() {
this.message = 'Good!'
},
mouseleave: function() {
this.message = 'Hover Me!'
}
}
});
body {
background: #333;
}
body #mouse {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: block;
width: 280px;
height: 50px;
margin: 0 auto;
line-height: 50px;
text-align: center;
color: #fff;
background: #007db9;
}
body #mouse a {
display: block;
width: 100%;
height: 100%;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="mouse">
<a @mouseover="mouseover" @mouseleave="mouseleave">
{{message}}
</a>
</div>
这个不起作用,因为事件监听是在代码中完成的。
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#mouse',
data: {
message: 'Hover Me!'
},
methods: {
mouseover: function() {
this.message = 'Good!'
},
mouseleave: function() {
this.message = 'Hover Me!'
},
mounted() {
this.$on('mouseleave', this.mouseleave);
}
}
});
body {
background: #333;
}
body #mouse {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: block;
width: 280px;
height: 50px;
margin: 0 auto;
line-height: 50px;
text-align: center;
color: #fff;
background: #007db9;
}
body #mouse a {
display: block;
width: 100%;
height: 100%;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="mouse">
<a @mouseover="mouseover">
{{message}}
</a>
</div>
从组件本身而不是在 html 中手动监听 mouseleave
事件的正确方法是什么?
最佳答案
在第二个片段中,mounted
钩子(Hook)函数应该在方法之外,这不会解决问题,并且 vm.$on
函数用于自定义事件而不是像 click
和 mouseleave
这样的原生事件,如解释的 here
:
如果你调用它:
vm.$on('test', function (msg) {
console.log(msg)
})
你应该在某处有如下代码:
vm.$emit('test', 'hi')
由于您无法使用this.$on
方法,我建议您使用以下解决方案ref
通过提供 link
或您想要的任何内容,将 ref
属性添加到您的 a
元素,并在 mounted 钩子(Hook)中添加以下代码:
this.$refs.link.addEventListener('mouseleave', () => {
this.mouseleave()
}, false);
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#mouse',
data: {
message: 'Hover Me!'
},
methods: {
mouseover: function() {
this.message = 'Good!'
},
mouseleave: function() {
this.message = 'Hover Me!'
}
},
mounted() {
this.$refs.link.addEventListener('mouseleave', () => {
this.mouseleave()
}, false);
}
});
body {
background: #333;
}
body #mouse {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: block;
width: 280px;
height: 50px;
margin: 0 auto;
line-height: 50px;
text-align: center;
color: #fff;
background: #007db9;
}
body #mouse a {
display: block;
width: 100%;
height: 100%;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="mouse">
<a @mouseover="mouseover" ref="link">
{{message}}
</a>
</div>
关于javascript - Vue实例中手动监听鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976357/