I created a form component Form.vue
which is a child from PostPage.vue
.
Inside 'Form.vue' i want to send a $emit for the parent to change a Prop value btn-text
.
Parent Component PostPage.vue
:
<template>
<div id="post-page">
<div class="header-text pt-5 text-center">
<div class="h2 font-weight-bold">
Welcome to the DevTribe Community
</div>
<div class="h5 font-weight-bold">
Ask questions, share content, introduce yourself. Be nice!
</div>
</div>
<Form />
<!-- textarea-not-clear isn't catched here below -->
<Posts
:btn-text="btnText"
@textarea-not-clear="changeBtnText()"
/>
</div>
</template>
<script>
import Form from './PostPage/Form.vue';
import Posts from './PostPage/Posts.vue';
export default {
name: 'PostPage',
components: {
Form,
Posts
},
data() {
return {
}
},
methods: {
changeBtnText() {
console.log('tss');
}
}
}
</script>
<style lang="scss" scoped>
#post-page {
background-color: #ffffff;
height: 100%;
padding: 0 20%;
}
</style>
The emit will be fired in a watch
, if the textarea is empty
Child Component Form.vue
:
<template>
<div id="form">
<form class="text-area text-center mt-5 mx-auto w-100">
<div class="row">
<div class="col-12">
<textarea
v-model="textarea"
name="post-text"
rows="6"
class="w-100"
placeholder="Create a post..."
/>
</div>
<div class="col text-left">
<button
type="button"
class="btn btn-outline-primary"
>
Send
</button>
</div>
</div>
</form>
</div>
</template>
<script>
export default {
name: 'Form',
data() {
return {
textarea: ''
}
},
watch: {
textarea: function() {
if (this.textarea !== '') {
this.$emit('textarea-not-clear', 'Join Discussion');
}
}
}
}
</script>
<style lang="scss" scoped>
.text-area {
height: 300px;
textarea {
border: solid black 1px;
}
button {
width: 120px;
}
}
</style>
I can see the event fired in Vue extension for DevTool:
but for some reason it is not possible to catch that event, the changeBtnText()
function inside PostPage.vue
won't be triggered and gives not even a console.log('test')
First things first. Form
is not a good name for a component as it clashes with a standard HTML element. I'm surprised you aren't getting a warning about this. See https://v2.vuejs.org/v2/style-guide/#Multi-word-component-names-essential
Next up, the problem with your event is that you're listening to the wrong component.
<Form />
<!-- textarea-not-clear isn't catched here below -->
<Posts
:btn-text="btnText"
@textarea-not-clear="changeBtnText()"
/>
The event is being fired by the Form
component but your listener is on the Posts
component.
I would also highly recommend that you stop using ids on your components and uses classes for styling instead.