The Vue emit function within a parent-child component relationship is disrupting the v-model binding

Currently troubleshooting a bug in another person's code and looking to minimize the amount of changes needed.

Encountering an issue where v-model binding in components is lost when using the $emit functionality to execute functions between child and parent components.

First, we have the parent component:

ParentComponent.vue

<template>
    <child-component v-bind:items="this.items"
                     v-on:event_child="this.eventUpdater">
    </child-component>
<template>
<script>
    import ChildComponent from './ChildComponent.vue';
    export default {
        components: {
            'child-component': ChildComponent
        },
        methods: {
            getItemDetails() {
                //...ajax request that loads item details for page.
            },
            eventUpdater: function(id) {
                this.getItemDetails();
            }
        }
    }
</script>

Next, we have the child component:

ChildComponent.vue

<template>
    <div v-for="item in items">
        <input v-model="item.itemId">
    </div>
    <button v-on:click="updateItems">update</button>
</template>
<script>
    export default {
        props: ['items'],
        methods: {
            updateItems() {
                //...ajax call that updates items.
                this.emitWhat();
            },
            emitWhat: function () {
                this.$emit('event_child');
            }
        }
    }
</script>

Following the update of the initial item (which works correctly), attempting to update another item results in the v-model for that item not functioning properly. Is the $emit functionality disrupting the v-model binding after the initial load? How can this issue be resolved?

Answer №1

Here is the current code snippet being used:

    <child-component v-bind:items="this.items"
                 v-on:event_child="this.eventUpdater">

It should be updated to this:

<child-component v-bind:items="items"
    v-on:event_child="eventUpdater">

The unnecessary this. has been removed.

Additionally, the items data property was not found in the parent component.

Update:

If the id parameter is defined in the eventUpdater: function(id) method, it should be emitted as follows:

<template>
    <div v-for="item in items">
        <input v-model="item.itemId">
    </div>
    <button v-on:click="updateItems(item.itemId)">update</button>
</template>

        updateItems(id) {
            //...ajax call that updates items.
            this.emitWhat(id);
        },
        emitWhat: function (id) {
            this.$emit('event_child', id);
        }

Update 2:

There may be an issue with having v-model on item.itemId:

<input v-model="item.itemId">

Consider binding v-model to newItems like this:

<input v-model="newItems[itemId]">

data(){
  return {
    newItems: [],
    //...
  };
}

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

Error in parsing JSON: An unexpected token < was encountered at the beginning of the JSON input, causing a SyntaxError at position 0 when parsing with

I need to transfer an array from a PHP file to JavaScript and save it in a JavaScript array. Below is the snippet of JavaScript code: xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 ...

Getting data in a ng-Dialog Modal with AngularJS is a breeze!

Hi there, I'm new to Angular JS and facing an issue with displaying data from my MySQL database in a table as well as in a modal for more detailed information: I've included the HTML file named _detail_modal.html at the bottom of the page. ...

Separating Angular code into distinct components

My page contains two input fields: one is for email and the other is a text field. Currently, everything is functioning correctly. However, I now want to split the component into two parts. For example, I have a 'basic-info' component currently. ...

Having trouble displaying information in a table using React JS

I devised a feature to display one column of a table and one column for checkboxes (each row should have a checkbox). I stored this file in a component folder with the intention of creating a page where the user selects an account type, and then a new tabl ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

I'm currently attempting to establish a connection between my server.js express API and MongoDB, but I keep encountering an unfamiliar error message that I'm having trouble decipher

Here is the server.js code: import express from 'express'; import bodyParser from 'body-parser'; import userRoutes from './routes/users.js'; import mongoose from 'mongoose'; co ...

I am looking to integrate VueJs to add inputs to an HTML form

Hey there, I'm looking to dynamically add input fields to an HTML form. Here's the HTML code snippet: <div class="form-group"> <a @click="addInput" clas ...

Modify the getAttribute value if it is null

I'm currently working on a project where I need to compile the answers selected in a quiz into a document. However, I've encountered a roadblock when certain questions are skipped based on previous responses. This leads to an error message: Un ...

Incorporating marker tags to different sections of text within a contenteditable div

The main objective of this feature is to enable users to select placeholders within message templates (variable names enclosed in %). Inspired by Dribbble The API provides strings in the following format: "Hello %First_Name% %Middle_Name% %Last_Name% ...

Is there a Vue library for page transitions that mimics the effect of Flutter Hero?

Check out the Vue Hero Transition package here. Explore the Vue Hero package on NPM. After reviewing various hero animation packages, I believe these two are worth mentioning. However, is there a library that receives more recognition based on star rati ...

How to update the date format in v-text-field

I have run into an issue while working on a Vue.js project that utilizes Vuetify. The problem lies with the default date format of the v-text-field when its type is set to "date." Currently, the format shows as mm/dd/yyyy, but I need it to display in the y ...

Attempting to access the 'name' field from an input element in an HTML document using AngularJS, and also introducing a static field named 'likes' with a value

Currently, I am in the process of developing an application that retrieves a list of Beers from an API. Each beer in the JSON response contains the fields {name: "beer", id: number, likes: number}. However, I am facing a challenge while attempting to add ...

Determining the number of words in every line within a textarea

I am looking to determine the number of words per line in a textarea. The width of the textarea is variable. Check out this code snippet that calculates the number of rows: http://jsfiddle.net/2tcygj9e/ ...

Rearrange the sequence of numbers using JQuery when an HTML element is deleted

I'm currently working on a simple functionality where I have 5 rows, each with its own number. So initially, the rows are numbered from 5 to 1. If I remove a value like 3, the sequence should adjust to 4, 2, 1, indicating that I now have only 4 rows ...

Create a personalized form with HTML and JQuery

Currently, the data is displayed on a page in the following format: AB123 | LHRLAX | J9 I7 C9 D9 A6 | -0655 0910 -------------------------------------------------------- CF1153 | LHRLAX | I7 J7 Z9 T9 V7 | -0910 1305 ---------------- ...

Display an image using a modal window and Ajax XMLHttpRequest

I was tasked with creating a button that can load various types of content (text, images, videos, etc) into a modal popup window using Ajax without any frameworks. So far, I've been successful with text but have run into issues with loading images. De ...

Having a Jquery resizing problem? No worries! When the width is less than 768, simply enable the click option. And when the width is

HTML <div class="profile"> <a href="#" class="hoverdropdown" onclick="return false;">Profile</a> <ul class="dropdown" style="display: none;"> <li><a href="#">Dashboard&l ...

PHP question about maintaining data continuously

So, I've created this interesting JavaScript 'thing' with the help of jQuery and AJAX. The main concept behind it is that a div can be edited (contenteditable=true), which sparked the idea to develop a chatroom-like feature. It's pretty ...

How about starting a Node.js application with specific configurations?

Is there a way to develop a Node.js app that can be initiated with additional parameters? Here are a few examples: node myApp.js -nolog This command would initialize the app with the custom parameter noLog=true, preventing console logging. node myApp.js ...

Error in NodeJS: 'Cannot alter headers once they have been sent.'

My project involves developing an app with Express that fetches tweets from Twitter. Each API call retrieves 200 tweets (or fewer if there are less than 200) and in total, I need to retrieve 1800 tweets. To achieve this, I use a time interval to make multi ...