Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code:

Child Component

<template>
   <input
      type="text"
      @input="setField($event.target.value, 'title')"
   />
   <wysiwyg-input
      @change="(text) => setField(text, 'content')"
   />
</template>

<script>
export default {
methods: {
    setField(value, field) {
      this.$emit("input", {
        title: field === "title" && value,
        content: field === "content" && value,
      });
    },
  },
}
</script>

Parent Component

<template>
  <FormFields v-model="blogPost" />
</template>

<script>

export default {
  data() {
    return {
      blogPost: {},
    };
  },
  watch: {
    blogPost(val) {
      console.log(val);
    },
  },
};
</script>

In this scenario, entering content causes the title field to become false. How can I modify the condition in the child component so that both inputs can be emitted to the parent component? Alternatively, do you have any other ideas to achieve the same goal?

CodeSandbox link: https://codesandbox.io/s/mystifying-benz-w8wgu?file=/src/App.vue

Answer β„–1

Utilize the ternary operator like this:

this.$emit("input", {
   heading: field === "heading" ? value : "",
   body: field === "body" ? value : "",
});

Answer β„–2

According to information found in the MDN documentation

The && operator actually provides the value of one of the specified operands

expr1 && expr2

If expr1 can be converted to true, it returns expr2; otherwise, it returns expr1

const a = 3;
const b = -2;

console.log(a > 0 && b > 0); // This results in false because `a > 0` is true and b > 0 is false.

In your scenario

if field is 'title',

field === "title" && value
will return value

if field is 'somethingelse',

field === "title" && value
will return false.

As Serg pointed out, you can utilize the ternary operator to address your problem.

this.$emit("input", {
   title: field === "title" ? value : "",
   content: field === "content" ? value : "",
});

Answer β„–3

Great Question

Why is the this.value not being used in the child component? You have passed v-model="blogPost" from the parent component to the child component, but it is not utilized in the child component.

Here's a possible solution:

In the Child Component:

<template>
   <input
      type="text"
      @input="setField($event.target.value, 'title')"
   />
   <wysiwyg-input
      @change="(text) => setField(text, 'content')"
   />
</template>

<script>
export default {
props: {
  value: {
    type: Object
  }
},
methods: {
    setField(value, field) {
      this.$emit("input", {
        title: field === "title" ? value : this.value.title,
        content: field === "content" ? value : this.value.content,
      });
    },
  },
}
</script>

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

Setting the overlay video to match the input video size in FFMPEG

Currently, I am incorporating FFMPEG wasm into a NextJS project. However, I believe that general FFMPEG solutions will suffice since FFMPEG wasm is capable of interpreting standard FFMPEG commands. My objective is to superimpose an overlay video onto the ...

A problem arises when trying to showcase the content in a responsive manner on the hamburger menu, particularly when viewing on mobile

As a newcomer to web development, I decided to challenge myself by building an E-Commerce website to enhance my skills. To ensure mobile responsiveness, I opted for a hamburger menu to hide the navbar content. However, despite resizing working flawlessly, ...

"Troubleshooting issue: Unable to retrieve grid data from Google Sheets API v4 when integrated

I've implemented a function within a React component that retrieves JSON data from an API request and logs it: async function getAllSheets() { let response; try { response = await window.gapi.client.sheets.spreadsheets.values.batchGet( ...

The display and concealment of a div will shift positions based on the sequence in which its associated buttons are clicked

I am in need of assistance with coding (I am still learning, so please excuse any syntax errors). What I am trying to achieve is having two buttons (button A and button B) that can toggle the visibility of their respective divs (div A and div B), which sh ...

Assistance needed with implementing jQuery tabs

I'm looking to add a link that takes me directly to content within a non-default tab on another page. Here's the code snippet that explains what I need: My Code: This is from my profile_edit.php page: The javascript: <script src="Javascrip ...

Using the onreadystatechange method is the preferred way to activate a XMLHttpRequest, as I am unable to trigger it using other methods

I have a table in my HTML that contains names, and I want to implement a feature where clicking on a name will trigger an 'Alert' popup with additional details about the person. To achieve this, I am planning to use XMLHttpRequest to send the nam ...

Load components dynamically and place them in a flexible position based on the context

UPDATE (After gaining a better understanding of the issue): I'm trying to display a component based on where the user clicks (specifically, which table row). Using ng2-smart-table, I've encountered an issue where there isn't a suitable sele ...

retrieve data from jsp page using ajax request

I've coded this JSP snippet Map<String, Long> map = new HashMap<String, Long>(); map.put("A", 10L); map.put("B", 20L); map.put("C", 30L); JSONObject json = new JSONObject(); json.accumulate ...

Route Separation with ExpressJS and Socket.IO

As I delve into the world of ExpressJS and Socket.IO, I find myself facing a puzzling situation. My routes are neatly organized in a separate file that I include from my app.js: var express = require('express') , db = require('./db&ap ...

One-way communication between two clients using Socket.io

While working on a basic socket.io application using React and Express, I've encountered an issue where two clients are facing difficulties in sending data to each other. For instance: Player 1 connects to the server followed by Player 2. Player 1 ...

Interact with a modal element using puppeteer

I'm having trouble clicking on the email login button inside a modal using Puppeteer for automation. The code is not able to find the modal element. Can someone assist me in debugging this issue? const puppeteer = require('puppeteer'); ( ...

Learn the steps for assigning a distribution tag to an npm package within a private registry

Operating with my own exclusive Gemfury repository, I am actively releasing npm packages. Intrigued by the prospect of applying distribution tags to my packages (as per this guide: https://docs.npmjs.com/cli/dist-tag). The configuration of my npm registr ...

Issues regarding ambient getters and setters

Recently, I encountered an issue with my open-source library called Firemodel. The library utilizes ES classes and getters/setters within those classes. Everything was working smoothly until my VueJS frontend code started flagging every instance of these g ...

Why does the implementation of my interface differ from what is specified in the TypeScript documentation?

Currently delving into the world of TypeScript documentation https://www.typescriptlang.org/docs/handbook/2/classes.html Specifically focusing on the section implements Clauses, an interesting revelation surfaces: A Word of Caution It’s worth noting t ...

Enhancing TypeScript - Managing Variables within Namespace/Scope

Why is the console.log inside the function correctly logging the object, but after the function returns it logs undefined, failing to update the variable? In addition, when using this within testNameSpace, it returns window. Why is that? namespace testNa ...

Tips for evaluating the build size of a Create React App and ways to minimize it

Currently, I've been following the steps outlined in this helpful guide: https://create-react-app.dev/docs/analyzing-the-bundle-size/ and I'm gearing up to execute the analyze command to assess my app's size. Is this approach the most effect ...

Display the hidden element using jQuery with the !important rule

There is a specific element that has been given a class with the following CSS styling: .cls { display:none !important; } Despite attempting to display this element using jQuery $(".cls").show(); This method does not seem to be effective. Is ...

Using nuxt.js to populate a Vuetify table with data

I am encountering issues with fetching data into a vuetify table, as it is not displaying any data within the table. My Laravel API Route::get('/businesslist', 'BusinessController@userlist')->name('businesslist'); Larav ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Steps to programmatically update Node modules:

I am looking to incorporate the use of npm update within a script. Take a look at my code snippet below: var npm = require('npm'); npm.load(function () { npm.commands.outdated({json: true}, function (err, data) { //console.log(data); npm ...