Mastering the art of connecting multiple input fields in both parent and child components with the Vue3 composition API

Currently, I am delving into learning Vue 3 with the composition API, but I have encountered some roadblocks. Specifically, I am working on a parent page that looks like this:

<template>
  <q-page class="flex flex-center bg-dark row">
    <q-input
      filled
      v-model="customerModel"
      @change="setCustomer"
      dark
    />
     <RegistartionForm />
  </q-page>
</template>

<script>
import RegistartionForm from "components/RegisterComponent.vue";
import { ref } from "vue";

export default {
  components: {
    RegistartionForm,
  },
  setup() {
    const customerModel = ref("");
    return {
      customerModel,
      onSubmit() {
        console.log(customerModel.value);
      },
    };
  },
};
</script>

Within my Vue component, which looks like this:

<template>
  <q-card
    class="q-pa-md sc-logon-card bg-dark col-lg-4 col-sm-12"
    align="center"
  >
    <q-input filled v-model="customerComponentModel" dark />
    <q-btn
      type="submit"
      @click="onSubmit"
    />
  </q-card>
</template>

<script>
import { ref } from "vue";
export default {
  name: "RegistartionForm",
  props: {},
  setup(props) {
    const customerComponentModel = ref("");
    return {
      customerComponentModel,
      onSubmit() {
        console.log(customerComponentModel.value);
      },
    };
  },
};
</script>

I am struggling to figure out how to bind the inputs for customerModel and customerComponentModel. Essentially, any changes made to the customerModel input should also affect the customerComponentModel input, and vice versa. Additionally, I need to implement submit logic in the component.

Thank you in advance for your assistance!

Answer №1

Make sure to utilize the v-model directive:

<RegistartionForm v-model="customerModel"/>

within the child component:

<template>
  <input type="text" v-model="customerComponentModel" />
</template>
<script>
import { computed } from 'vue';
export default {
  props: {
    modelValue: String,
  },
  setup(props, { emit }) {
    const customerComponentModel = computed({
      get: () => props.modelValue,
      set: (value) => emit("update:modelValue", value),
    });

    return { customerComponentModel };
  },
};

By binding customerModel and customerComponentModel together, any alterations made to customerModel will also impact customerComponentModel and vice versa. For more information on v-model and components, check out this resource

Answer №2

<template>
  <q-page class="flex flex-center bg-dark row">
    <q-input
      filled
      v-model="customerModel"
      @change="setCustomer"
      dark
    />
     <RegistartionForm :customerModel="customerModel"/>
  </q-page>
</template>

Vue component:

<script>
import { computed } from "vue";
export default {
  name: "RegistartionForm",
  props: {customerModel: String},
  setup(props) {    
    const customerComponentModel = computed(() => {
      return props.customerModel
    })
    onSubmit = () => {
        console.log(customerComponentModel.value);
      }

    return {
      customerComponentModel,
      onSubmit      
    };
  },
};
</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

Use jQuery or javascript to eliminate the 'Webpage Dialog' from the 'showModalDialog' window

At one point on the page, I have a line of code that looks like this: onclick="window.showModalDialog("http://rauf-thecoder.blogspot.com/");" When executed, it displays the following: Is there a way to eliminate the title bar text for the Webpage Dialog ...

Implementing a password prompt in CodeIgniter using JavaScript

I need to delete a teacher as an admin, but before doing so, I want to require them to re-enter their password. However, I'm having trouble getting the delete function to work even though the prompt is displayed. Can someone help me figure out what I& ...

Guide to making type-safe web service requests using Typescript

When utilizing Angular for web service calls, it's important to note that the type of the returned object is not automatically verified. For example, let's say I have a Typescript class named Course: export class Course { constructor( publ ...

Create an if statement that depends on the current URL without explicitly mentioning it

I am currently working on a project to display specific RSS feeds based on the current URL. I have made some progress with my solution below, but I am looking for a way to dynamically check the current URL and pull the corresponding RSS feed instead of spe ...

Issues encountered when incorporating personalized CSS into a Vuetify element

Working with the Vuetify selector input component, v-select, and wanting to customize its style led me to inspecting it in Chrome and copying down the necessary classes. For instance, to change the font size of the active value, I utilized: .v-select__sel ...

"Sending the selected pass selector as a parameter to the dispatched action is causing a typing

When a selector changes its value, I want to trigger an action. To achieve this, I passed the selector with a subscription instead of passing an observable. selectedSchedulingsOnPopup$ = this.store.pipe(select(selectSchedulingsByBranch)); this.store.disp ...

Issue with ng-hide logic malfunctioning

I am currently developing an Ionic application and encountering some issues with the ng-hide directive. My goal is to display or hide a button based on whether the user has completed registration. The button in question: <button class="button button-c ...

How to connect site pages in WordPress using Vue.js

I'm currently in the process of revamping a website using the vuejs framework and I've started off with this boilerplate as my foundation. My experience with vuejs is very fresh, just 3 days old, so I'm still trying to understand how to crea ...

Mastering Generic Types in Functions in Typescript

My current structure looks like this: export interface Complex { getId<T>(entity: T): string } const test: Complex = { getId<Number>(entity){return "1"} // encountering an error 'entity is implicitly any' } I am wondering w ...

The vuestrap spinner is struggling to catch the shown event

https://github.com/yuche/vue-strap/blob/master/src/Spinner.vue https://github.com/yuche/vue-strap/blob/master/docs/example/spinnerDocs.vue Upon reviewing the provided example, I have attempted to replicate the same functionality here: https://jsfiddle.net ...

Generate a list of files and transfer them to an input file

I am currently working on creating a drag and drop area where I can retrieve dataTransfer items using webkitGetAsEntry, and then differentiate between directories and files. My goal is to convert these files into a FileList and transfer them to a file inp ...

Ensuring Form Accuracy - Mandatory Selection from Group

Currently, in the project I am working on, there are three textboxes that need to be validated to ensure at least one of them has been filled out. I have been researching custom validation with Angular directives and found that it is possible to set the v ...

Encountering a problem when trying to submit data on a form in Prisma Nextjs due to an

As I construct an editing feature for objects within my postgres database, I am encountering an issue related to form submission. Specifically, when attempting to update fields defined in the schema, I am receiving an error message: client_fetch_error unde ...

Displaying Keystonejs list items on every page

Is there a more effective method to efficiently load the content of a Keystone's list on every page, rather than calling it individually in each view? Could this be achieved through middleware.js? The objective is to create a dropdown for the navigat ...

Using Three.js to spin a mesh in the direction of a sphere

As a newcomer to Three js, I've been grappling with a challenge lately. My 3D model is currently facing a specific direction, surrounded by a sphere. Before I move the mesh, I want to animate its rotation so that it aligns with the specified sphere. ...

Unable to locate module '.next/server/font-manifest.json'

I'm encountering a frustrating issue while attempting to deploy my nextjs app with server rendering. The app was created using Azure Pipelines and then uploaded to a production server that runs on a Linux operating system. Below is the configuration ...

Using identical content in various template slots

Is it possible in vuejs to assign the same content to multiple slots without repeating it? For example: <base-layout> <template slot="option"> <span :class="'flag-icon-' props.option.toLowerCase()" />{{ countriesByCode ...

There seems to be an issue with my view loading CSS/JS files that are not located within

I have been working on my MVC 3 application and encountered some challenges with loading CSS, images, and JS files from the root folder. When I tried to run my view located in the Views folder, I faced the following output: <link href="@Url.Content("~ ...

Is there a way to search through an array of object arrays in JavaScript for a specific key/value pair using lodash or any other function?

I am faced with a task involving an array of objects. Each object has a key that needs to be used to search through sets of arrays containing similar objects. The goal is to determine if all the arrays contain the same value for a specific key in my object ...

Delay the axios get request in the useEffect

Working with React JS, I have implemented a useEffect hook to request data from a database via an Express server when the page renders. However, if the server is down, the app will continue to make thousands of requests until it crashes. Is there a way to ...