Passing data from a child component to a parent in Vue.js using emit, without the need for a button

In my template form, each question is contained within a child component structure as shown below:

   <template>
      <question1
         @display-answer-1="setAnswer1"
      />
      <!-- other child components here... -->
   </template>
   
   <script>
   
   import Question1 from '...path...';
   
   export default{

      components: { Question1 },
      data() {
         answer1: ''
      },
      methods: {
         setAnswer1(answer1) {
             this.answer1 = answer1;
         }
      }
   };

The structure of the child component is as follows:

<template>
   <input type="text" v-model="answer1"/>
   <div>
       <button
             type="button"
             @click="saveQ2"
       >Save
       </button>
   </div>
</template>

<script>

export default {
    data() {
        return {
            answer1: ''
        };
    },
    methods: {
        saveQ2() {
            const answer1 = this.answer1;
            this.$emit('display-answer-1', answer1);
        }
    }
};

Although the current code functions correctly, it requires adding a "Save" button for each question to transfer data from the child to the parent. Are there any alternative solutions to avoid placing a save button under each question?

Answer №1

If you want to trigger an event when an input loses focus, you can utilize the blur event.

<template>
<input @blur="saveQ2" type="text" v-model="answer1"/>
</template>

<script>

export default {
data() {
    return {
        answer1: ''
    };
},
methods: {
    saveQ2() {
        const answer1 = this.answer1;
        this.$emit('display-answer-1', answer1);
    }
}

};

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

The play button in videojs is unresponsive when incorporated into JavaScript responses

I've been trying to implement a video player using video.js, but I'm running into issues with the play button not responding to my JavaScript code. I have all the necessary scripts included in my file, but I haven't been able to find a solut ...

Error in Passport JS: Trying to use an undefined function

I've been struggling with debugging my code in Express and Passport. I've tried following solutions from others but can't seem to get it right. Any help or useful links would be greatly appreciated. Here is the error message along with the ...

"Click here to access the downloadable content obtained through web scraping

I am looking to automate a task using Python where I need to get a PDF file from a website with fileid 8426 and date 03312021. Visit this link: Click on the "Download PDF" button Save the downloaded file to a directory After exploring, I came across a P ...

Utilizing Ajax in conjunction with Ruby on Rails

I have a question that may be quite basic (I am new to Rails 3). I am looking to implement Ajax functionality where once a user clicks on a link, it triggers a $.post call and initiates some server-side changes. Within the _share partial file, I currently ...

What is the best way to incorporate a fresh array into the existing array element stored in local storage?

I stored a group of users in the local storage: let btnSignUp = document.getElementById("btnSignUp"); btnSignUp.addEventListener('click', (e) => { let existingUsers = JSON.parse(localStorage.getItem("allUsers")); if (existingUsers == null ...

Verify the presence of a specific select option using text in jQuery version 1.7

Looking at the following snippet of HTML: <select id="sel"> <option value="0">Option1</option> <option value="1">Option2</option> <option value="2">Option3</option> <option value="3">Option4</option> & ...

In search of a new object value to update

Looking to update the value of a specific object key in an array? Here is the code snippet where I want to make this change. I only want to replace the value under Mon, not the entire array length. The key weekday will be provided dynamically. array = [ ...

Trouble accessing data property within a method in Vue 3 with Typescript

I am facing an issue with accessing my data in a method I have written. I am getting a Typescript error TS2339 which states that the property does not exist in the type. TS2339: Property 'players' does not exist on type '{ onAddPlayers(): vo ...

A guide on leveraging Vue class components alongside the composition API in Vue2 using TypeScript

<script lang="ts"> import { Component, Vue } from 'vue-property-decorator' import { CustomerContext, getCustomerRepository } from '@/composables/customerRepository' @Component export default class CustomerList extends V ...

Unnecessary Page Diversion

Within my index.php file, I have a download button with the id of "render". Using AJAX, I am sending a request to the server. The JavaScript code being utilized is as follows: $('#render').click(function(e){ $('html,body').animat ...

When working with Node.js and Express, I encountered an issue where the req.session object was not defined within

It's peculiar to me that req.session.username is undefined in the tag >>>DOESNT WORK<<< while it works in the tag >>>THIS DOES WORK<<<. I passed req as an argument to my module, but it seems like there might be some ...

Foundation and equalizer do not provide an optimal user experience

I am new to using Foundation. Currently, I am utilizing Foundation 5 along with equalizer. I have a row with 2 columns - one containing text and the other containing an image. I want both columns to have the same height, so I am using data-equalizer. ...

Utilizing Google Maps API Version 3 to create interactive infoBubbles using an

Are there any recommended Google Maps v3 infoBubble examples that anyone has come across or knows of? I am interested in utilizing an array of data for this, but I'm unsure if there are any effective applications available or if it can be easily impl ...

Sorting by number or date in indexedDB may lead to unexpected results due to the

I have set up an index in my database called time on the created_at field: var os = thisDB.createObjectStore(name, { keyPath : "id" }); os.createIndex("time", "created_at", {unique: false }); Instead of storing the time as a standard date format, I conv ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

Working with Vue.js and Axios: Extracting data from a nested Axios response

I am currently working on a project that involves Vue.js, TypeScript, and Axios. My main focus is on creating a complex ApiRequest. Unlike the traditional method of fetching data using axios directly in the component, I wanted to find a more maintainable s ...

Using a template element for looping over an array with conditional rendering

I'm facing a challenge with conditionally rendering elements in a list using Petite-Vue. When I try to place a <li> tag with a v-if attribute inside a <template> tag with a v-for attribute, an error is generated: Uncaught (in promise) Ty ...

What Could be causing the Electron Vibrancy Effect to be malfunctioning?

This issue is really baffling me because I can't pinpoint where the problem lies. In my previous project using older versions of Electron on the same machine, everything worked fine when I used vibrancy. But now, it's not working and I have no c ...

Reactjs and Isotope offer the ability to expand and collapse on click. In this unique feature, only one item can be expanded at

Currently, I am working on refining an isotope application where each item expands upon clicking it and collapses when another item is clicked. However, the issue I am facing is that multiple cells can be opened simultaneously. I am looking for the most ef ...

backbone.js router failing to recognize URL fragments

I have set up a basic router in my code and initialized it. Issue: I encountered an unexpected behavior when visiting the URL http://localhost/backbone1/#photos/5. Despite expecting an output from console.log() in the JavaScript console, nothing appears. ...