Retrieving information from defined component in Vue

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>

Answer №1

To make the necessary changes, update the template as follows:

<div class="container" id="app">
    <tweet-postbox @add-tweet="addTweet"></tweet-postbox>
</div>

By using @add-tweet, you can set up an event listener for the add-tweet event. It is recommended to use kebab case to prevent any browser case-sensitivity issues. When emitting the event, make sure to use the same name like so:

this.$emit('add-tweet', response)
. For more information, refer to the official documentation.

The section ="addTweet" assigns the method addTweet to act as the listener.

Visit https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers for more details.

Answer №2

Here is a fantastic answer I came across in another post:

Snippet for Component 1:

<!-- language: lang-js -->

    this.$root.$emit('eventing', data);

Snippet for Component 2:
<!-- language: lang-js -->

    mounted() {
        this.$root.$on('eventing', data => {
            console.log(data);
        });
    }

Answer №3

To begin with, it's essential to address the issues in your coding style, which include indentation errors. Consider utilizing a tool like eslint to help improve your code quality.

Next, let's dissect the line this.$emit('addTweet'):

  • The keyword this in this context refers to the Vue component instance, specifically an instance of TweetPostBox.
  • By calling $emit with addTweet, you are triggering an event within the component.

Once the addTweet event is emitted, Vue will search for any event handlers assigned to it and execute them accordingly.

In your current scenario, there are no event handlers set up for this particular event. The function addTweet in your parent component is strictly a local function and not an event listener.

To create an event listener, Vue offers the @ syntax, similar to how you use @click. So, instead of @click="dosomething" (for handling the onClick event), you should use @add-tweet for the addTweet event. (Note: @addTweet works as well, but adhering to coding standards, Vue will automatically convert it for you)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on utilizing the carousel component in Bootstrap and populating it with data generated from Node.js

My goal is to design a carousel that displays 5 different pieces of information pulled from a separate app.js file. I attempted to implement a forEach loop, but encountered issues when trying to create a second Bootstrap carousel container. Here's th ...

Transform a PHP array into a JavaScript array with UTF-8 encoding

I am currently facing an issue with a products table that contains foreign characters. My goal is to utilize a PHP array in JavaScript to filter a dropdown box as the user types. Everything seems to be working fine except when encountering foreign characte ...

Unable to retrieve scripts upon returning to the main page of a Jquery website

Starting fresh with this post, I'm feeling incredibly frustrated and close to giving up on JQM completely. This shouldn't be so difficult. Here's my website structure: OUI/ index.php js/ pages/ images/ On the index.php page at http://loca ...

Get rid of the title on Superfish Menu in Drupal 7

Exploring Drupal for the first time, I've been able to find solutions to all my queries except one - removing the "Main Menu" header from my superfish menu. The region called superfish has successfully had superfish added to it, but I'm unable t ...

Does a .innerXML exist?

Is anyone knowledgeable in XML able to offer some assistance? I have a function that I use to parse XML data, and you can find the XML file I am working with here. function dialogXML(varName,url){ if (window.XMLHttpRequest){ r[varName]=new XML ...

PHP array utilized in a dynamic dropdown menu

I am working on creating a PHP array for a select list that has dynamic options populated using JavaScript. My goal is to collect all the options selected and display them on the next page. I was wondering if there is a better way to achieve this task. C ...

Despite setting allowHalfOpen to True, Node.js: Client still disconnects from Server

I've been working on a Node.js script that involves creating a server if a specific port is available, or connecting to an existing server if the port is already in use. To achieve this, I am using a recursive approach based on a reference from this l ...

Getting Started with Parsing JSON Objects in ReactJS

In my ReactJS project, I am trying to parse through a JSON list using the following model: public class ModelEmployee { public List<Employeelist> Employees { get; set; } public int count { get; set; } public int Pagenumber { get; set; } ...

Version 10 of Internet Explorer seems to be overlooking the XMLHttpRequest setting of 'xhr.withCredentials = true'

Encountering an issue with a cross-domain ajax call in IE10 (in IE10 mode, not compatibility). Situation: Two domains involved, http://a and http://b. Cookie set for http://b. Currently on page http://a. Goal is to make a CORS request to http://b using X ...

Animating computed values with VueJS transitions

I am looking to create an animated block of posts that can be filtered. When certain filters are applied, a computed method filteredPosts is triggered and assigned to a component like this: <block-article :posts="filteredPosts" /> Within my <blo ...

Enhancing Vue.js functionality with v-model for seamless global data access

I am currently developing a web application that allows users to collaborate on projects. The app's architecture is structured in the following manner: Component A (the main app container) Components B1-Bn (including header, footer, and main window, ...

Is it possible to check if something is "ready" by using a combination of setTimeout and recursive functions?

I am currently working on a solution to determine when an asynchronous call is "ready" or not. I have a function that uses $.ajax which, upon success, sets a boolean variable in the global scope and some other data. Prior to making the ajax call, the boole ...

Why is there an issue with the way I am defining this Javascript variable?

In my JavaScript file, milktruck.js, I have defined an object called TruckModel. My goal is to create an array of TruckModel objects because in my multiplayer game, I cannot predict how many players will enter or exit at any given time. The issue I am fa ...

The async/await feature is not pausing for the completion of the async.map function call

I'm encountering an issue in my Node.js app where I need to gather and format data using a helper function for an API endpoint. The problem arises when trying to loop through an array and make asynchronous calls to the database for each entry. Despite ...

The error message "Cannot read property 'addEventListener' of undefined" occurred while trying to register the service worker using `navigator.serviceWorker.register('worker.js')`

I'm grappling with a JavaScript issue and need some help. You can find the demo of the functioning script by the author right here. I've implemented the same code as displayed on his demo page. I've downloaded the worker.js file and ...

In JavaScript, the code is designed to recognize and return one specific file type for a group of files that have similar formats (such as 'mp4' or 'm4v' being recognized as 'MOV')

I am working on a populateTable function where I want to merge different file types read from a JSON file into one display type. Specifically, I am trying to combine mp4 and m4v files into MOV format. However, despite not encountering any errors in my code ...

Ways to close jQuery Tools Overlay with a click, regardless of its location

I have integrated the Overlay effect from jQuery Tools to my website, with the "Minimum Setup" option. However, I noticed that in order to close it, the user has to specifically target a small circle in the upper right corner which can affect usability. It ...

Using Javascript, the sum of inputs is calculated based on the keyup event

I am a beginner in javascript and I'm learning about events. Below is the HTML code for a table that displays income titles and their respective prices. <table class="table table-hover table-bordered" id="incomeId"> <thead> <tr&g ...

Combining the first name, last name, and code in Javascript

I'm attempting to combine the initial letter of both names with the randomly generated code. var firstname = prompt("Please input your first name."); var lastname = prompt ("Please input your last name."); if (amountCorrect >= 4){ ...

Ensure the CSS class stays on Quill clipboard.dangerouslyPasteHTML

One of the challenges I face with using the Quill Text Editor is that when I use the method clipboard.dangerouslyPasteHTML to paste HTML into the editor, it does not maintain custom CSS classes. For example: let content= '<p class="perso-clas ...