Refs a slot to define the parent function

Refs a slot to define the parent function



I have 2 components:


slot content


submit


cancel



So I want to actually define the submit method, what it does, in the ContractForm component (child) but use it in the Modal component(parent)?


submit method


ContractForm component


Modal component



My code



I tried to ref the ContractForm component and call the method defined in the ContractFormfrom the Modal component like this.


ContractForm component


ContractForm


Modal component


<modal>
<contract-form ref="modalcontent"></contract-form>
</modal>


<template>
<div class="modal">
<slot :submit-modal="submitModal" ref="modalContent"></slot>
<button @click="submitModal">Submit</button>
</div>
</template>

<script>
export default {
methods:
submitModal: function ()
this.$refs.modalcontent.submitModal()
,

</script>


<template>
<div>
<p>Modal content</p>
</div>
</template>

<script>
export default
methods:
submitModal: function ()
alert('test')
,


</script>



The problem



The reference doesn't work, when I console.log(this.$refs) this returns an empty object. I think the refs does'nt work because this is a slot(innerHtml)


console.log(this.$refs)


refs


slot



Someone can help me please ?
Thanks




1 Answer
1



You're right in your assumption that the slot tag cannot be referenced using a ref tag.


slot


ref



In your case, it'd be better to have the modal component emit a submit event when the "Submit" button is clicked:


submit


<template>
<div class="modal">
<slot></slot>
<button @click="$emit('submit')">Submit</button>
</div>
</template>



And then in the parent component scope, you can specify that the form component's submitModal function is the handler for the modal's submit event.


submitModal


submit


<modal @submit="$refs.modalcontent.submitModal()">
<contract-form ref="modalcontent"></contract-form>
</modal>






Thanks it's exactly what I need!

– Bruno MC
Sep 14 '18 at 16:01



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ