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 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.
Thanks it's exactly what I need!
– Bruno MC
Sep 14 '18 at 16:01