Transferring data from a child component to a parent component in Vue without the need for a click

In my Vue project, I have a parent component called ChangeInfo which contains a child component named ShowWorkInfo. The ShowWorkInfo component includes several input forms for updating job information. To manage the data input, I created an object variable called work_info and used v-model to bind the form fields. However, I'm unsure how to pass this data from the child component to the parent component without any buttons in the child component. I am considering whether it would be better to combine everything into the ChangeInfo component instead of splitting it up. Here is a snippet of my code.

ChangeInfo (parent component)

export default class ChangeInfo extends Vue {
  public isUpdated: boolean = false
 // Rest of the script remains unchanged...

I make use of two functions like so:

<template>
  <div class="d-block">
    <ShowProfile />
    <ShowWorkInfo :isUpdated="isUpdated" @update-work-info="updateWorkInfo" />
    <ShowPersonalInfo
      :isUpdated="isUpdated"
      @update-personal-info="updatePersonalInfo"
    />
    <div class="w--27 mw-100 mx-auto my-9">
      <button
        @click="triggerSubmit"
        v-b-modal="'update-success'"
        class="btn btn-primary w-100"
      >
        {{ $t('common.btn.btn_update') }}
      </button>
    </div>
    <ModalUpdateSuccess />
  </div>
</template>

Answer №1

There are several approaches to achieve this:

  1. One quick and simple method is to pass another prop from the parent component to the child component. This prop should be set to true when the common.btn.btn_update button is pressed. In the updateWorkInfo function, you can set up a watcher in the child component for this prop. When the prop changes to true, emit ('submitted', data) to send the data back to the parent component and handle the submit event there.

// Code for Parent script
// Some code here

I'm not particularly fond of this approach, but it does work as intended!

  1. A more traditional way would be to include the submit button within the child component and emit a submitted event along with the data. This approach is cleaner and promotes reusability:

// Code for Parent script
// Some code here
<!-- Parent template -->
// Template code here
<!-- End of Parent template -->

<!-- Child template -->
// Template code here
<!-- End of Child template -->

Please note that there are other variations of achieving this functionality. If you're interested, feel free to ask. The methods mentioned above are some of the most commonly used ones I've encountered.

UPDATE: Form validation has been added in the first block. Feel free to try it out! However, if you require field-level validation, it's recommended to move the submit logic to the child component.

Answer №2

It may not be the conventional approach, but here's an alternative method. Imagine a scenario where you don't have a button to trigger sending information to a parent component. In such cases, we can utilize watch and v-model with lazy loading.

This is just a simple example and not directly related to your code.

ChildComponent:


<template>
  <div class="hello">
    <input type="text" placeholder="Enter something" v-model.lazy="myObj.message">
    <input type="text" placeholder="Enter something" v-model.lazy="myObj.name"> 
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  data () {
    return {
      myObj : {
        message:"",
        name : ""
      }
    }
  },
  watch: {
    myObj : {
      handler (newVal) {
      this.$emit('change', newVal)
    },
    deep: true
    }
  }
};
</script>

ParentComponent:


<template>
  <div id="app">
    <HelloWorld @change="change"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  methods: {
    change (obj) {
      console.log(obj)
    }
  }
};
</script>

The console will display your message once you click outside the input field. If v.model.lazy is not used, any changes in the input will trigger data transmission immediately. Feel free to test it out to see if it fits your requirements.

EDIT: I have included deep:true in order to watch the entire object. This allows you to specifically log obj.name or obj.message in the parent component.

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

What makes TypeScript code run successfully using `node` instead of `ts-node` by mistake?

I have created a basic node.js project using TypeScript. Here is the content of my package.json file, which lists all the packages I have installed (without including ts-node): { "name": "mydemo", "version": "1.0.0", "description": "", "main": "ind ...

Discovering the type in Typescript without explicitly defining a type variable for the callback

I am looking for a solution to wrap rxjs subscribe's next callback with my own function: type Handler<T> = (value: T) => void; export function withTryCatch<T>(callback?: Handler<T>): Handler<T> { return (value: T) => ...

Converting an existing array into a TypeScript string literal type: A step-by-step guide

Converting TypeScript Arrays to String Literal Types delves into the creation of a string literal type from an array. The question raised is whether it's feasible to derive a string literal from an existing array. Using the same example: const furnit ...

Issues arising from using async/await in conjunction with .then() in vue.js login function, causing fetch process not to wait for completion

I implemented a login function to verify credentials on my backend server, but I am facing an issue with waiting for the server response. Despite following the es7-async-await.js guide and trying various async/await and promise techniques, the function sti ...

Using Typescript to create a union of functions

There are two different types of functions: one that returns a string and the other that returns a Promise<string>. Now, I am looking to create a function that can wrap both types, but I need to be able to distinguish between them when invoking the f ...

Apply CSS styling to the shadow root

In my preact project, I am creating a Shadow DOM and injecting a style element into the Shadow root using the following code: import style from "./layout/main.css"; loader(window, defaultConfig, window.document.currentScript, (el, config) => ...

The usage of Angular Tap is no longer recommended or supported

My Angular application contains the following HTTP interceptor: import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpResponse } from '@angular/common/http'; ...

Generating dynamic slots in VueJS allows for the creation of

Creating slots dynamically from an array is my current task. After some tinkering, I've managed to make it work using the following code snippet: <template v-for="(department,id) in departments" v-slot:[id]="record"> < ...

Troubleshooting Checkbox Validation Problem in Vue JS

Deactivating Vue js Validation In the following piece of code, I am trying to disable a checkbox when item.status == "active". I attempted to use :disbale="item.status='active'"" in my checkbox. With this code snippet, the ...

Sorting Json Data Using Vue

My experience with Vue.js led me to a challenge I can't quite figure out: how to filter specific data in a Json file. Let me provide more context: I have a Json file filled with various electronics products such as computers, mice, keyboards, etc. I w ...

Does Virtual DOM speed up or slow down applications?

After reading through the Svelte JS documentation, I noticed that one of its advantages is the absence of a Virtual DOM, making apps built with this framework faster and lighter. However, conflicting information suggests that having a Virtual DOM can act ...

Easy Nested Dynamic Routing

My goal is to utilize a modal within a nested route to execute a specific task for each object. For instance, the '/objects/2' route includes a <nuxt-child/> component for adding comments in a modal using the route path '/objects/2/add ...

Display the navigation icon when the menu is open on small screens or mobile devices in Vue.js

I'm facing an issue with displaying the navigation icon on mobile screens. Below is the code snippet: export default { data () { return { navIcon:false } }, computed:{ }, methods:{ reversedMessage: function () { ...

Exploring the integration of React.Components with apollo-client and TypeScript

I am in the process of creating a basic React component using apollo-client alongside TypeScript. This particular component is responsible for fetching a list of articles and displaying them. Here's the code: import * as React from 'react' ...

Using a function that is passed down from a parent component into a child component

One of my components has a parent-child relationship: <select-school-type placeholder="Filter by school type" @selected="getSchools"></select-school-type> I want the "getSchools" method to be triggered when the user changes ...

Unable to utilize MUI Dialog within a ReactDOMServer.renderToStaticMarkup() call

I recently started using the DIALOG component for the first time, expecting it to seamlessly integrate into my setup. However, much to my disappointment, it did not work as expected. After spending a considerable amount of time troubleshooting the issue, I ...

The error message "Identifier 'title' is not defined. '{}' does not contain such a member angular 8" indicates that the title variable is not recognized or defined in the

Here is the code snippet of my component: import { Router, ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { CategoriesService } from 'src/app/categories.service'; import { P ...

What is causing the error message "may require a suitable loader" to appear when I add my TypeScript Node module to my Next.js application?

After developing a TypeScript node module and integrating it into my Next.js app, I encountered an error when attempting to run the app. Are you aware of any reason why this issue may be occurring? Please refer to the information provided below. Details a ...

Using Next.JS useRouter to access a dynamic route will result in receiving an empty object as the return value

I've encountered an issue with dynamic routing in my specialized calendar application built with Next.JS. One of my pages is working perfectly fine while the other is not functioning at all. The first page (working): // pages/date/[year]/[month]/[day ...

Font modification is unsuccessful in Vue-Material

Here is a snippet from my App.vue file where I encountered an issue with changing the font in the md-tabs component, taken from . The CSS line: background: #42A5F5; works perfectly fine, but this one does not: color: #E3F2FD; App.vue: <template> ...