See this simple modal ponent:
Vueponent('modal-content', {
template: `
<div class="modal">
...
</div>
`,
props: ['title'],
});
How can I control keyboard press from the ponents that use it (parents)?
If I use @keyup.esc event then it does not have any effect:
<portal to="modal-wrap">
<modal-content @keyup.esc="doSomething">
</modal-content>
</portal>
If I put @keyup.esc in the modal-content ponent on the DIV then it works, but that's no use to me because I need to call the doSomething
function which exists in the parent ponent
See this simple modal ponent:
Vue.ponent('modal-content', {
template: `
<div class="modal">
...
</div>
`,
props: ['title'],
});
How can I control keyboard press from the ponents that use it (parents)?
If I use @keyup.esc event then it does not have any effect:
<portal to="modal-wrap">
<modal-content @keyup.esc="doSomething">
</modal-content>
</portal>
If I put @keyup.esc in the modal-content ponent on the DIV then it works, but that's no use to me because I need to call the doSomething
function which exists in the parent ponent
3 Answers
Reset to default 6The reason your code is not working is because your you are trying to listen to a native browser event - which is not emitted by Vue, but by the DOM itself.
To react to these type of events you have to attach your listener to an actual HTMLElement
- not a vue ponent. Since this is a mon issue, vue provides a simple modifier that automatically attaches the eventlistener to the underlying HTMLElement
: the .native
modifier.
Try it like this
<portal to="modal-wrap">
<modal-content @keyup.esc.native="doSomething">
</modal-content>
</portal>
You can find further information in vues documentation
You could do something like this in your doSomething function:
onClickButton (event) {
this.$emit('clicked', 'someValue')
}
And in you parent ponent do this:
<template>
<parent-ponent @clicked="handleClick"></parent-ponent>
</template>
For more info check this:
https://v2.vuejs/v2/guide/ponents.html#Listening-to-Child-Components-Events
And this:
https://medium./js-dojo/ponent-munication-in-vue-js-ca8b591d7efa
Use refs (Accessing Child Component Instances & Child Elements)
<modal-content @keyup.esc="doSomething" ref="modal">
then inside the doSomething method:
this.$refs.modal.close();
presuming you have a close()
method in the modal-content ponent.
You could also pass a prop, like you are doing with title
:
<modal-content @keyup.esc="modalIsOpen = false" :modalIsOpen="modalIsOpen">
Vue.ponent('modal-content', {
template: `
<div class="modal" :class="{show: modalIsOpen}">
...
</div>
`,
props: ['title' 'modalIsOpen'],
//...
});