我正在尝试从子组件中侦听子组件中的鼠标事件,但没有触发该事件。当我用html监听事件时它起作用,但是不起作用
如您所见,它起作用:
userWrapperDiv
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;
}
从组件本身而不是在HTML中手动监听<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="mouse">
<a @mouseover="mouseover">
{{message}}
</a>
</div>
事件的正确方法是什么?
答案 0 :(得分:1)
在第二个片段中,mounted
钩子函数应该在方法之外,这不能解决问题,并且vm.$on
函数用于自定义事件,而不用于本地事件像click
和mouseleave
之类的,如解释的here
一样:
如果您这样称呼:
vm.$on('test', function (msg) {
console.log(msg)
})
您应该在某处输入类似以下代码的代码:
vm.$emit('test', 'hi')
由于您无法使用this.$on
方法,因此我建议您使用ref
的以下解决方案,方法是将ref
属性添加到您的a
元素中,并赋予{{ 1}}或您想要的任何内容,并在挂接的钩子中添加以下代码:
link
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;
}