我已经为这个问题绞尽脑汁了好几个小时了。我看不出有什么问题,根据我所能说的,我正在遵循这里的文档:https://vuejs.org/v2/guide/components-custom-events.html
下面的代码
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="wrap">
<test-listen>
<test-emit></test-emit>
</test-listen>
</div>
<script>
Vue.component('test-listen', {
data: function(){
return {};
},
methods: {
customHandler : function(e){
console.log(e);
console.log("works");
}
},
template: `
<div class='test_listen' v-on:custom="customHandler">
<slot></slot>
</div>
`
});
Vue.component('test-emit',{
data: function(){
return {};
},
methods: {
clickHandler : function(){
this.$emit('custom');
}
},
template : `
<div class='test_emit' v-on:click="clickHandler">
test
</div>
`
});
new Vue({
el:"#wrap"
});
</script>
<style>
.test_listen{
display:block;
padding:20px;
border:1px solid #000;
}
.test_emit{
display:block;
width:100px;
height:100px;
background-color:#f0f;
color:#fff;
font-weight:700;
font-size:20px;
}
</style>
但是监听器肯定是绑定到元素的,因为如果我发送一个vanillaJS CustomEvent,它就会很好地触发控制台日志。我遗漏了什么?
发布于 2018-05-11 03:25:06
这里有两件事是错误的。
我猜
如果你真的想不受限制地到处传递数据,最好使用 Global Event Bus Approach
您的代码的
工作示例,只做了一些细微的修改。
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="wrap">
<test-listen>
</test-listen>
</div>
<script>
Vue.component('test-listen', {
data: function(){
return {};
},
methods: {
customHandler : function(e){
console.log(e);
console.log("works");
}
},
template: `
<div class='test_listen' >
<test-emit v-on:custom="customHandler"></test-emit>
</div>
`
});
Vue.component('test-emit',{
data: function(){
return {};
},
methods: {
clickHandler : function(e){
// e => event : didnt pass here as console will stuck so
this.$emit('custom', 'somedata');
}
},
template : `
<div class='test_emit' v-on:click="clickHandler">
test
</div>
`
});
new Vue({
el:"#wrap"
});
</script>
<style>
.test_listen{
display:block;
padding:20px;
border:1px solid #000;
}
.test_emit{
display:block;
width:100px;
height:100px;
background-color:#f0f;
color:#fff;
font-weight:700;
font-size:20px;
}
</style>
发布于 2018-05-11 03:12:19
我在这里只看到一个错误。您应该将v-on
添加到子组件中。当你从内部执行$emit('custom')
时,它会在父组件上调用"customHandler“。
<test-listen>
<test-emit v-on:custom="customHandler"></test-emit>
</test-listen>
发布于 2018-05-11 03:06:00
With this.$emit()
是对父组件说,嘿,我创建了一个事件,现在你可以监听这个事件了
你做得很好,但是你没有在父组件中监听由子组件发出的事件。I made it to work.Click here to see it in action
因此,为了让您的代码正常工作,在test-listen组件中,使用test-emit组件作为子组件。
然后在div #wrap
中使用测试侦听组件
你的问题是你没有监听父组件中的事件。
https://stackoverflow.com/questions/50278842
复制相似问题