Connecting a text input in a nested component to the data passed down from its parent component in VueJS

My VueJS setup involves a child component sending data to a parent component, which then tries to route the data to a sibling of the child to create new components. I'm using a dictionary to group the data and push it into an array. The array is then looped through with a v-for loop to populate the new components. While this approach may not be optimal, it's what I have currently implemented. I am open to suggestions for better alternatives.

Unfortunately, the current implementation is not working as expected. I am only able to get one out of three strings to show up where intended. More details will follow after I present the code snippet.

Attempts made so far:

I have tried various versions of the code, including using a simple v-for loop in a list, as well as different iterations with or without dictionaries or arrays.

In my troubleshooting process, I have referenced the official VueJS documentation, searched through online resources, but have not found a solution yet.

Below is a stripped-down version of the main App.vue file:

<template>
    <div id="app">
        <img alt="Vue logo" src="./assets/logo.png">

        <TweetDeck v-on:messageFromTweetDeck="msgReceived($event)"/>

        <TwitterMsg v-for="(tweet, index) in tweets" :key="index" 
        :name="tweet.name" :handle="tweet.handle" tsp=3 :msg="tweet.tweet" />

        <TwitterMsg name="aaa" handle='aaa'
        tsp=50 msg="hey this is a message on twitter"/>


        <input type="text" v-model="placeholderText"/>

    </div>
</template>

<script>
import TwitterMsg from './components/TwitterMsg.vue'
import TweetDeck from './components/TweetDeck.vue'

export default {
    name: 'app',
    components: {
        TwitterMsg,
        TweetDeck

    },

    data: function() {
        return {
            tweets: [],
            message: "",
            placeholderText: ""
        }
    },

    methods: {
        msgReceived(theTweet, name, handle) {
            this.tweets.push({tweet: theTweet, name: name, handle: handle})
        }
    }
}
</script>

The relevant content of the TweetDeck.vue file is provided below:

<template>
    <div>
        <input type='text' v-model="yourName">
        <input type='text' v-model="yourHandle">
        <input type='text' v-model="yourTweet"/>
        <button type='button' @click="sendTweet()">Tweet</button>
    </div>
</template>

<script>
    export default {
        name: "TweetDeck",

    data: function() {
        return {
            yourName: "Your name here",
            yourHandle: "Your twitter handle",
            yourTweet: "What's going on?"
        }
    },

    methods: {
        sendTweet() {
            this.$emit('messageFromTweetDeck', this.yourTweet, this.yourName, this.yourHandle);

        }
    }
}

</script>

You can also find the less significant TwitterMsg.vue file included here (which mirrors features of Twitter):

<template>
    <div>
        <h4>{{ name }}</h4>
        <span>@{{ handle }}</span>
        <span> {{ tsp }}</span> <!-- Time Since Posting = tsp -->
        <span>{{ msg }}</span>
        <img src='../assets/twit_reply.png'/><span>1</span>
        <img src="../assets/twit_retweet.png"/><span>2</span>
        <img src="../assets/twit_fave.png"/><span>3</span>

    </div>
</template>

<script>
    export default {
        name: "TwitterMsg",
        props: {
            name: String,
            handle: String,
            tsp: String,
            msg: String
        }
    }
</script>

<style>
    img {
        width: 30px;
        height: 30px;
    }
</style>

Expected outcome: The code should generate a new TwitterMsg component with the correct name, handle, and message data every time the "Tweet" button is clicked.

Actual results: Despite successfully passing the tweet message from TweetDeck.vue to TwitterMsg.vue, the name and handle strings do not reach their intended destination within the components.

I am somewhat disoriented as I am relatively new to VueJS, but I take comfort in the fact that at least one piece of string data is being displayed correctly. 🎉

Answer â„–1

To start, make sure to eliminate the requirement for the $event parameter

<TweetDeck v-on:messageFromTweetDeck="msgReceived"/>

Next, enhance the data structure being sent to the parent component:

sendTweet() {
  this.$emit("messageFromTweetDeck",
    { tweet: this.yourTweet, name: this.yourName, handle: this.yourHandle }
  );
}

Afterwards, update your msgReceived function:

msgReceived(childData) {
  this.tweets.push(childData);
}

Link: codesandbox

Hope this assists 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

It is essential for each child in a list to be assigned a unique "key" prop to ensure proper rendering, even after the key has been assigned (in Next

Working with Next JS and implementing a sidebar with custom accordions (created as SideAccord.js component). Data is being looped through an array with assigned keys, but still encountering the following error: Warning: Each child in a list should have a u ...

Customize the appearance of polygons in OpenLayers 2 by adjusting the fill color and opacity

I am aiming to use different fill colors and opacity values for various shapes (such as Triangle, Circle, Square, Hexagon, etc.). Although I can draw the shapes, set different titles, and stroke colors with the code below, I'm struggling to define th ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

How can I ensure that VueJS only starts loading data after the initial API call has been completed?

After retrieving data from an API, I populate a form in my component. The challenge I am facing is that the watchers are triggered immediately after populating the initial data. I want them to be triggered asynchronously. Additionally, I need to prevent th ...

Executing numerous Ajax requests within a single Rails view

Two ajax requests are being used on a single page, one showcasing a date and the other displaying a calendar. The first request updates the date upon clicking a date on the calendar. The second request allows for switching between months on the calendar. ...

What could be causing the function to not work properly within the React component?

Having trouble with a React component utilizing speech recognition for converting speech to text. Initialized the recognition functions within the component but encountering errors. Need assistance in troubleshooting this issue. const speechRecognition = w ...

Why isn't the Nunjucks extends directive functioning when the template is stored in a different directory and being used

I have successfully integrated nunjucks templating into my express app. Below is the directory structure of my project: . nunjucks-project |__ api |__ node_modules |__ views |__ templates |__ layouts |__ default.html ...

Imitating the Frameset Separator's Actions

The latest HTML5 specification has eliminated the <frameset> element. One useful feature of the <frameset> tag that is hard to replicate without it is: In a frameset, you can adjust the position of the frame divider line with the mouse. Is t ...

The AdminLTE Bootstrap Table Search Bar vanishes when extra <th> tags are added

Currently facing difficulties with the table functionality in AdminLTE. By default, AdminLTE includes a search and organization feature in its table structure. When I insert some table data using PHP, everything looks fine. However, when I attempt to add ...

The $resources headers have not been updated

My objective is to include a header with each HTTP request for an ngResource (specifically, an auth token). This solution somewhat accomplishes that: app.factory('User', ['$resource','$window', function($resource,$window,l ...

Errors are being displayed in the console when attempting to use Vuex getters in a component. This is happening because the Vuex state properties are still null at the time the getters

When assigning results from GET requests to my Vuex state properties, it's expected that they won't be available instantly. However, I have a getter like the following: findChampion: (state) => (id) => { let championId = id.toString() ...

I am trying to showcase a collection of images on my homepage, but unfortunately, it is not functioning as expected

Does anyone know how to display images using Angular? I am currently utilizing the pic controller in an AngularJS file. Any assistance would be greatly appreciated. HTML CODE <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

"Utilizing vue-multiselect to manage two independent controls accessing the same data source without any

Greetings to all of you experts in Vue and JavaScript! I currently have an array of values ["A", "B", "C", "D"] A user is required to select values into two separate lists, namely "List1" and "List2". It's important that the values chosen in one lis ...

A guide on displaying data in a table using a select dropdown in a pug file and passing it to another pug file

After creating a single page featuring a select dropdown containing various book titles from a JSON file, I encountered an issue. Upon selecting a book and clicking submit (similar to this image), the intention was for it to redirect to another page named ...

Issue with Ionic 2's infinite scroll not triggering method on second scroll attempt

I utilized the ion-tab element to showcase a page (inboxitem) which encompasses ion-list and makes use of ion-infinite-scroll. The following code snippet resides in inboxitem.html <ion-content class="inbox can-swipe-list"> <ion-list> ...

Setting a menu item as active in a SvelteKit app: A step-by-step guide

I encountered an issue with the main navigation menu in my sveltekit application. The problem is that when the app is loaded or refreshed, the active menu item corresponding to the current URL is not set. After struggling to find a solution online, I manag ...

Having trouble with importing files from a different folder in a React Typescript project

I have a specific folder arrangement set up https://i.sstatic.net/GFOYv.png My goal is to bring both MessageList.tsx and MessageSent.tsx into my Chat.tsx file // Chat.tsx import React from 'react' import {MessageList, MessageSent} from "./ ...

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...