Tips for transferring v-model data between components

I am working with a parent form component and a child component, both located in separate files. I am using the Quasar Framework components. How can I pass data from the parent to the child component using v-model?

Parent Component

<template>
  <q-input
    label="Name *"
    lazy-rules
    :rules="[val => (val && val.length > 0) || 'Please enter your name']"
    v-model="name"
  />
</template>

<script>
export default {
  name: "Name",
  data() {
    return {
      name: "Max"
    };
  }
};
</script>

Child Component

<template>
  <div class="q-pa-md" style="max-width: 500px">
  <q-form @reset="onReset" class="q-gutter-md">
      <Nome> </Nome>              
      <div>
   <q-btn label="Reset" type="reset" color="red" flat class="q-ml-sm" />
      </div>
    </q-form>
  </div>
</template>

<script>
import Name from "components/Name.vue";
export default {
  components: { Name },  

  onReset() {
    this.name = null;
  }
};
</script>

How does the onReset() function work in this setup?

This content has been automatically translated.

Answer №1

It appears there may be some confusion regarding the relationship between your child component and parent component in the code. In this scenario, Nome serves as the child component while the form that utilizes Nome acts as the parent component.

If you need to reset the Nome component from the parent form component, you can utilize the ref attribute to call the reset method.

For a practical demonstration, see the code below:

Vue.component("nome-input", {
data(){
  return {
    input: ""
    }
  },
  template: `
  <input @input="onInput" type="text" v-model="input">
  `,
  methods: {
  reset(){
    this.input = ""
    },
    onInput(){
    this.$emit('onInput', this.input);
    }
  }
});
Vue.component("user-form", {
data(){
  return {
    name: '',
    }
  },
  components: {
  },
  template: `
  <div>
  {{name}}
    <nome-input ref="nome" @onInput="updateName"></nome-input>
    <button @click.prevent="save">Save</button>
    <button @click.prevent="reset">reset</button>
  </div>
  `,
  methods: {
  save(){
    console.log(this.name);
    },
    reset(){
    this.name = "";
    this.$refs.nome.reset();
    },
    updateName(value){
    this.name = value;
    }
  }
  
});

new Vue({
  el: "#app",
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
  <user-form></user-form>
</div>
</body>
</html>

View a live demo of the above code on jsfiddle: https://jsfiddle.net/azs06/u4x9jw62/34/

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

Delete an item from an array when a dropdown selection is made

When dealing with Angular 8, I encountered a logic issue. There are two drop-down menus: First Drop-down The options in the first menu are populated from an array of objects Example Code, ts: {rs_id: "a5f100d5-bc88-4456-b507-1161575f8819", ...

Is there a way to stop users from altering form values on a webpage by using the "inspect" tool in their browser?

Currently, I am developing an application using node.js and handlebars as the view engine. One issue I am facing is that when a form is submitted, it inserts data into the database. The problem arises because the form passes values that are hidden from the ...

Tips on passing methods to form provider with unique name for managing nested forms

As discussed in #60277873, when creating nested forms, it is necessary to rename the methods of the nested form as follows: const { register, formState: { errors }, handleSubmit, } = useForm({ mode: "onBlur", }); This code sh ...

React Error boundary is failing to perform as anticipated

Having issues implementing an error boundary in React. Here is the code snippet: ErrorBoundary.js import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: fal ...

I'm looking for guidance on how to properly implement onChange in this particular script. Any help with the correct syntax

Can someone help me with the correct syntax for writing onChange in this script? I want to integrate these phpcode into my script. Here is the Javascript code: ih+='<div class="form-group drop_bottom" id="select_one_'+extra_num+'">< ...

Streaming HTTP content on a domain secured with HTTPS using HTML5

Is it possible to stream HTTP on an HTTPS domain without triggering browser security errors? By default, the browser tends to block such requests. I rely on the hls.js library for desktop support with .m3u8 files. When I play content directly (on mobile o ...

Experiencing difficulties in displaying a React element that is being passed as a prop

One of my components looks like this: const Chip = (props) => { const ChipIcon = props.icon; let deleteButton = null; if (!props.readOnly) { deleteButton = <Delete style={styles.deleteButton} onTouchTap={props.onRemove} /& ...

Attempting to generate a fresh document by duplicating the data from a specific variable

Currently attempting to generate a new csv file within a specific directory. The goal is to save the data of a variable inside the created csv file: handleRequest(req, res) { var svcReq = req.body.svcReq; var csvRecData = JSON.stringify(req.bod ...

What is the best way to store multiple values in local storage using useState in react?

Currently, I am exploring how to utilize multiple values in the useState hook and perform CRUD operations in local storage. Here is an example of my code: const [Data,setData]=[[{ name:'luis', pass:'1234', //....... }]] // ...... ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

Angular - How child components can communicate with their parent components

I'm struggling to understand how to communicate between components and services. :( Even though I've read and tried a lot, some examples work but I still don't grasp why (?). My goal is to have one parent and two child components: dashboa ...

I would like to inquire about the process of accessing profile information on a website through the LinkedIn API

Do you know how I can use the latest LinkedIn JavaScript API with OAuth 2.0 to retrieve my own profile details for a website? The goal is to automatically update the website using my linked profile information. I have attempted the following: api_key: ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

Dealing with an empty request.FILES using FileUploadParser in Django Rest Framework and Angular file upload technique

Uploading files in an angular view can sometimes be tricky, especially when using templates. The code snippet below shows how to upload multiple and single files using Angular File Upload library. Multiple <input type="file" name="file" nv-file-select= ...

Unable to extract property from object in context due to its undefined status

Having trouble with the useContext hook in my React app for managing the cart state. Keep getting an error stating that the function I'm trying to destructure is undefined. I'm new to using the context API and have tried various solutions like e ...

What is the best way to secure videos and other static files with authentication in a next.js web application?

My goal is to provide static content, specifically videos, exclusively to authorized visitors. I want to secure routes so that they are only accessible to authenticated users. However, the challenge arises when trying to display a video on a page located i ...

When utilizing JavaScript syntax and performing API testing with Postman

Hello, I need some assistance from experts in connecting to Postman using the JavaScript code provided below. When running nodemon, the connection appears to be normal with no errors. Also, the GET request sent to Postman works fine. However, I am encounte ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

What causes the error message "Request payer account number does not match session" to appear when utilizing the PayPal smart button with multiple recipients?

Can I use login information or smart buttons to pay multiple payees? I attempted the following: paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ reference ...