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

What is the best way to utilize v-model with an array of strings in a Vuex store when using v-for

Encountered an issue while trying to set a value in an Array within the Vuex Store: VueCompilerError: v-model cannot be used on v-for or v-slot scope variables because they are not writable. Seeking alternatives to achieve this without creating a local co ...

Ajax versus embedding data directly into the HTML code

Currently, my project involves a combination of JavaScript with jQuery and communication with a Django backend. Some aspects of the user interface require Ajax due to the fact that data to be sent is dependent on user input. On the other hand, there is c ...

Utilizing JavaScript to handle the value from a selected form

My form is quite simple: <form id="signup"> <div class="form-group"> <input type="text" name="email" placeholder="Email" id="email" required> </div> <div class="form-group"> <input type= ...

express has a req.body that is devoid of any content

When making a request to my local server in my React app, the code looks like this: fetch("http://localhost:4000/signup", { method: "POST", mode: "no-cors", body: JSON.stringify({ name: "Joe", lname: "Doe& ...

Encountering an 'Uncaught TypeError' with Tumblr API due to undefined property 'type' not being read

I have multiple feeds on my website, each fetching posts from various tags. The first feed is functioning properly, but the 2nd and 3rd feeds are displaying the following error: Uncaught TypeError: Cannot read property 'type' of undefined All ...

How can you effectively transfer a parameter from .run to .config?

Currently, I am working on my angularjs ui-route project and have placed a variable called clientid in the .run() core function to store it in $rootScope. However, there comes a point where I need to access this stored variable within the .config() core. ...

The function of style.marginRight differs from that of style.marginLeft

One function aligns content to the left while the other doesn't align it to the right function openNavLeft() { document.getElementById("mySidenavLeft").style.width = "100vw"; document.getElementById("main").style.marginLeft = "100vw"; } function ...

Best practices for displaying a Multidimensional JSON Object using JavaScript

Within my current project, I have a JSON object structured as follows: { "face": [ { "attribute": { "age": { "range": 5, "value": 35 }, "gender": { "confidence ...

Ionic Vue is throwing an error indicating that a property is not found on the type '{ $route(currentRoute: any): void; }'

Currently, I am developing an Ionic WebApp using Vue and TypeScript. My current task involves retrieving the current id parsed by the route. To achieve this, I have been working on a watcher: export default { data() { return { ...

What is the solution for getting rid of the "clear sort" state in an angular-ui-grid column header?

I am looking for information on how to remove the default behavior where the 3rd click disables sort and stays "neutral" on sortable headers. Having a disable sort state seems flawed as it does not change the sort order. How can I eliminate the 3rd state ...

Updating an HTML Table with AJAX Technology

I'm struggling to figure out how to refresh an HTML table using AJAX. Since I'm not the website developer, I don't have access to the server-side information. I've been unable to find a way to reload the table on this specific page: I ...

Is there a more efficient method to select all the rows containing '1's in a specific cell within a large range of data?

As a beginner, I've developed a script that scans through a large table and extracts rows containing the value '1'. The table consists of approximately 2000 rows, so it's taking quite some time to process all of them. Is there a more e ...

Using jQuery to extract contact information from Google: A step-by-step guide

I'm currently using Google's API to access my contact list information and after logging the output in the console function fetch(token) { $.ajax({ url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token. ...

Concentrating on a Div Element in React

I'm trying to set up an onKeyPress event that will be triggered when a key is pressed while a 'Level' element is displayed. I know that the div needs to be focused for events to register, but I'm not sure how to do this with functional ...

Sign up for your own personalized Express and HBS helper now!

As a newcomer to Node, I appreciate your patience with me. I recently utilized the express generator module with the -hbs flag to switch from the default templating engine to Handlebars. Currently, I am attempting to register a custom helper to enable me ...

Exploring time differences in Javascript

I am trying to save a JSON AJAX response from the server in the browser's localStorage for a duration of one minute, along with a timestamp generated using new Date().getMinutes(). Upon triggering $(document).ready, I aim to check the stored timestam ...

When attempting to retrieve information using the findById(''), the process became frozen

When attempting to retrieve data using findById(), I'm encountering a problem. If I provide a correct ObjectID, the data is returned successfully. However, if I use an invalid ObjectID or an empty string, it gets stuck. If findById() is called with a ...

Strategies for capturing and incorporating Meteor.Error notifications from Meteor.Methods into a client-side database?

I am currently working on creating an error notification panel in Meteor. I have set up a client-side MongoDB, but I am encountering an issue with pushing Meteor.Error messages into that client-side database using the throwError function. Currently, the er ...

What is the best technique for evaluating different businesses' operating hours?

I am trying to compare the opening hours stored on my server with the current time. Here are the details: Start: 09.00 End: 00.30 The goal is to determine if the store is open or closed based on the current time. If the current time falls outside of t ...

AJAX parsing through JSON files generated by PHP

Need help with sending a json to an ajax call and reading it when it's sent. Plus, the json structure seems off due to the backslashes... This is the ajax function in question: function find(){ var type = $('#object_type').val( ...