What is the best way to transmit two distinct sets of data from a child component to the v-model of a parent component?

Currently, I am working on a project using vuejs 2 and typescript. In this project, I need to pass two different sets of data - data and attachments - within the parent component. I am utilizing vue-property-decorator for this purpose. However, I am facing difficulty referencing attachments while already using data in the Parent component with v-model. Can you guide me on the correct approach to solve this issue?

Parent Component

<template>
  <ChildComponent 
  v-model="data" 
  :attachments="attachments" How can I reference attachments ?
  />
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import ChildComponent from '~/components/ChildComponent'

@Component({
  components: {
    ChildComponent
  }
})
export default class ParentComponent extends Vue {
  data: any = {};
  attachments: any = [];
}
</script>

Child Component

<template>
  <form>
    <input type="text" v-model="data.firstname" />
    <input type="text" v-model="data.lastname" />
    <input type="file" multiple v-model="attachments" />
  </form>
</template>

<script lang="ts">
import { Component, VModel, Vue } from 'vue-property-decorator'

@Component
export default class ChildComponent extends Vue {
  @VModel() data!: any;
  @VModel() attachments!: any;
}
</script>

We appreciate your assistance and guidance.

Answer №1

This solution worked smoothly for me in a Vue3 Single File Component. While I didn't use TypeScript here, it shouldn't be too difficult to make the necessary conversions.

Big thanks to ChatGpt for the inspiration!

Here's the setup with a parent component using v-model:

<template>
  <ChildComponent v-model="parentData" />
  <p>Parent Data: {{ parentData }}</p>
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
import { ref } from 'vue';

const parentData = ref('');

</script>

The child component utilizes a watcher and emits changes to the parent (not my preferred method):

<template>
  <input v-model="modelValue" />
</template>

<script setup>
import { ref, watch, emit } from 'vue';

props: {
  modelValue: {
    type: Object,
    required: true
  }
},

const childData = ref('');

// Assign prop value to childData
childData.value = props.modelValue;

// Watch for changes in childData and emit updates to the parent component
watch(childData, (newValue) => {
  emit('update:modelValue', newValue);
});
</script>

I believe there's room for optimization, but for now, I'm calling it a day.

The use of 'update:x' syntax in emit is new to me; I initially hoped for a simpler binding approach, but no luck so far.

Fingers crossed for a more elegant solution from someone else.

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

Text field in React's material-ui causes the screen to shake

I am encountering an issue with a simple React code that includes a Material-UI Textfield. Whenever I try to enter data into the text field, the screen shakes. Additionally, when I click outside of the box after entering data, the screen shakes again. Ca ...

NextJS function utilizes its own references within React and automatically fetches data without the need for an import

I recently purchased this template and I'm trying to figure out which page the code snippet "{getLayout(<Component {...pageProps} />)}" is directed to during the initial load. It seems like it might be a global variable hidden somewher ...

Is it possible to process HTML and JavaScript as a request in JMeter?

After receiving a response, I noticed that the HTML body contains a hidden form along with an internal JavaScript function to submit the form (view snapshot here). Is there a method in JMeter to execute JavaScript code that directly submits a form? I am ...

Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there, I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on. Currently, I have an image displayed in an HTML page like this: <div id="tag_sunrise_sunset"><p ...

I'm puzzled by the inconsistency of my scrolltop function on mobile, as it seems to be scrolling to various parts of the page depending on my

I am encountering an issue with a function that scrolls to a specific element when a button is clicked. Strangely, this functionality works fine on desktop but fails on mobile devices. It successfully scrolls to the correct position only when at the top of ...

Utilize Ramda.js to transform commands into a functional programming approach

I have written a code to convert an array of numbers into a new datalist using imperative style. However, I am looking to convert it to functional style using a JavaScript library like ramdajs. Code Background: Let's say we have 5 coins in total with ...

Obtain the union type by extracting values from an indexed object

Suppose there is an indexed type: type X = { a: 'A', b: 'B' } Is there a way to derive the following type from it: type V = 'A' | 'B' without using an explicit method like this: type V = X['a'] | X[& ...

Javascript - Incorporate a hyperlink into my Flickr Api image query

I am struggling with incorporating a link around the image generated by this request due to my limited API knowledge. Below is the current function responsible for displaying the album images. To see a functional version, please refer to the provided fidd ...

Connection Error: Unable to Resolve Host Name socketIO

the issue I am facing is as follows: GET net::ERR_NAME_NOT_RESOLVED I have implemented an environment variable named VUE_APP_BACKEND_API using vuecli3 for the ip address. In addition to Vue.js, I am also utilizing VueSocketIO. I am unsure of the source ...

Make sure to name your Typescript component selector correctly, as it should not

As I work on my Angular project, I encountered a situation where one component needed to be referenced in the HTML of another component. To make this connection, I used kebab case for the selector like so: @Component({ selector: 'swiftlog-navbar&ap ...

What is the reason that this particular JQuery code is malfunctioning in the IE browser once integrated into my website?

Currently, I am utilizing the DDCharts jQuery plugin from DDCharts JQuery to incorporate some charts into my website. After downloading the plugin and testing it in various browsers, I encountered an issue specifically with Internet Explorer 8+. Strangely, ...

Issue with JQuery's parentsUntil method when using an element as a variable not producing the desired results

I'm having trouble with a specific coding issue that can be best illustrated through examples: For example, this code snippet works as expected: $(startContainer).parents().each(function(index, parentNode) { if (parentNode.isSameNode(commonConta ...

What happens if the document.ready function fails to execute?

Many JavaScript developers have encountered a situation where page elements are not available in the document.ready event because it fires too soon, especially when most parts of the page are loaded dynamically with AJAX. Currently, I am working with Drupa ...

Use AJAX to send a form submission along with an anchor tag

I've been facing a challenge trying to make this work, but unfortunately, I haven't had any success. Typically, all my forms include a submit input, and I handle AJAX submission in the following manner: <script> $("input#submit").click(fun ...

What are the different ways to share data between components in React?

There are two components in my code, one named <Add /> and the other named <Modal>. The <Add /> component has a state for handling click events. Whenever the <Add /> component is clicked, the state is set to true. I need to utilize ...

Step-by-step guide on building a mat-table with nested attributes as individual rows

Here is the data structure I am working with: const families = [ { name: "Alice", children: [ { name: "Sophia" }, { name: "Liam" ...

What is the best way to delete rows from a table that was created using a JQuery AJAX response?

I am currently working on a coding project where: The user is required to input a location, Clicks on a button to execute a GET call in order to fetch data based on the specified location, and A table is then filled with the retrieved data. My goal is t ...

What is preventing me from assigning to a class variable within a $http success handler?

During the course of my project, I have encountered a perplexing situation that is difficult to comprehend. My intuition tells me that the issue lies in a peculiar nuance of javascript while I am working in TypeScript. Unfortunately, I am unable to prove t ...

Tips for incorporating real-time data into your nodeJS and express applications

I am currently utilizing express for managing all the routing in my web application. Additionally, I have integrated firebase to store my data. For organization purposes, I decided to divide my code as follows: index.js: This file serves as the main node ...

Express.js - display the complete information

Trying to display an array of objects (highcharts points) is giving me some trouble. Instead of the actual data, I'm seeing [object Object]. It seems that JSON.stringify() doesn't play well with HTML. util.inspect also doesn't work as expe ...