Recently, I've been diving into Vue and learning about templates.
I discovered that you can pass data from a child
component to a parent
component using $emit()
.
app.js
Vue.component('tweet-postbox', require('./components/tweetPostBox.vue').default);
const app = new Vue({
el: '#app',
methods: {
addTweet (tweet) {
//Data received from the postTweet method in tweetPostBox.vue
console.log(tweet)
}
}
});
tweetPostBox.vue
<template>
<div class="post-box">
<div class="w-100 d-flex align-items-center">
<div class="profile-image rounded-circle"></div>
<input v-model="message" type="text" id="tweetText" placeholder="What's happening?">
</div>
<div class="controls d-flex align-items-center w-100">
<button class="btn btn-primary ml-auto" @click="postTweet" id="postTweet">Tweet</button>
</div>
</div>
</template>
<script>
export default {
data: function () {
return {
message: ''
}
},
methods: {
postTweet: async function(){
let response = await axios.post('/post', {
message: this.message
})
//How can I send this response data to the main Vue instance?
this.$emit('addTweet', response);
}
}
}
</script>
I'm struggling to retrieve the value in my app.js
from the component file... nothing is showing up in the console. What am I missing?
Update: Added HTML
<div class="container" id="app">
<tweet-postbox></tweet-postbox>
</div>