Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  110] [ 2]  / answers: 1 / hits: 25820  / 7 Years ago, sun, february 19, 2017, 12:00:00

This works, but I'm sure there is a much better way to do this. Please look at the document.getElementsByClassName() part near the bottom.



html:



<modal>
<a slot=trigger>Show Modal</a>
<h3 slot=header>My Heading</h3>
<p slot=body>Here is the body of the modal.</p>
<div slot=footer>
Here is the footer, with a button to close the modal.
<button class=close-modal>Close Modal</button>
</div>
</modal>


Modal.vue:



<template>
<span>
<span @click=show = true>
<slot name=trigger></slot>
</span>
<slot name=header></slot>
<slot name=body></slot>
<slot name=footer></slot>
</span>
</template>

<script>
export default {
data() {
return { show: false }
},
mounted(that = this) {
document.getElementsByClassName('close-modal')[0].addEventListener('click', function () {
that.show = false;
})
}
}
</script>


Is there a better way to do this?


More From » vue.js

 Answers
146

Yes there is and it's to emit close event from within modal component and than handle closing in parent component when close emit is received. I can't take credit because I saw this on official vue site here.


Basically in modal template


<button @click="$emit("close")">close </button>

And then in component where you use modal add open modal property in data


data:  function () { return { open: false }}

And when you use modal component


<modal @close="open = false">...</modal>

Mind @close is the event you emitted from modal it can be whatever @die works if you used $emit ("die") in modal.


And when you want to open modal you can use similar approach


<a @click="open = true">open modal</a>

If you do this its data driven and easy to reuse.


edit


Ok so if you want to add buttons from outside of modal component then define your slots and just add a button in one of those slots or all of them that will make open = false


[#58871] Friday, February 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grant

Total Points: 169
Total Questions: 96
Total Answers: 98

Location: Cape Verde
Member since Sat, Apr 24, 2021
3 Years ago
;