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

Leveraging various routes to access data with a shared VueJS 3 component

Could you please review this code snippet: It displays two routes that utilize the same component to fetch content from an API. Main.js const router = createRouter({ history: createWebHistory(), routes: [ { path: "/route1& ...

Step-by-step guide on transferring form data from an Ionic application to parse.com MBaaS through the REST API

Today is my first day with Ionic/Angular, and I'm diving in out of necessity. I've been using tutorials and documentation to create a demo/test app that submits data to the Parse.com MBaaS service. However, I seem to be stuck somewhere and clue ...

Using createElement and render function to pass props to a Vue instance from a .blade.php file

UPDATE: Additional details: In my main-page.blade.php file, I have the following code: //main-page.blade.php where vue instance will mount <div id="main-page" class=" bg-uoi-green"> <main-page :data=['one'] > ...

Converting this HTML/PHP code into JavaScript: A step-by-step guide

I have been struggling to convert this code into JavaScript in order to set the document.getElementById().innerHTML and display it in HTML. Can anyone assist with writing this code in JavaScript? <form action='create_new_invoice.php?name="<?php ...

Creating interactive functionality for textareas and input fields in Vue: A beginner's guide

I need assistance with creating a function where changing the input field will also automatically update the textarea's value. I have successfully implemented Vue js for updating the input field based on the textarea, but I am struggling to reverse th ...

What methods can I use to create a peer-to-peer communications platform with PHP, MySQL database, and JavaScript?

Currently, I am encountering the challenge of creating a communication channel between two users on a website (such as a gaming site) using only the technologies specified in the title. I recently created an online chess platform with the aim of allowing ...

Issue with jQuery .hover() not functioning as expected

The issue I'm encountering is just as described in the title. The code functions correctly on all divs except for one! $(".complete-wrapper-1").hide(); var panelHH = $(".file-select-wrapper").innerHeight; $(".files-button").hover(function(){ $(" ...

Exposing a Hidden Division with a Link via jQuery

I currently have a jQuery Panel set up to open when clicking a button. Now, I am looking to add a second link at the bottom of the page that will also open the same panel. Can anyone provide guidance on how to accomplish this? You can view my JSFiddle a ...

Feature exclusively displays malfunctioning image URLs for the web browser

Hello everyone! I've been diving into learning JavaScript and recently attempted to create a function that randomly selects an image from an array and displays it on the browser. Unfortunately, despite my efforts, all I see are broken link images. Her ...

Guide on converting a material datepicker date value into the format "MM-DD-YYYY" in Angular 6

I need help formatting the date below to MM-DD-YYYY format in my Angular 6 project. I've checked out various solutions on SO and other websites, but so far, none have worked for me. Currently, I am using Material's Angular DatePicker component. ...

Modifying the display toggle functions

How can I toggle between a button and an input type "file" when clicked? I am using jQuery to show and hide elements, but I need help changing back to the button when clicking somewhere else on the page. HTML: Upload<input type="button" id="upload" /& ...

In order to have the bot repeat a structure for every user, I would need to utilize both mongoose and discord.js

I am utilizing MongoDB (mongoose) to establish a database for storing user notes in my Discord bot, which is being developed with Discord.JS. This is my "Guild.js" file: const { Schema, model } = require('mongoose'); const Guild = Schema({ i ...

What is the best way to finish up the JavaScript code below?

Having just started learning JavaScript, I am struggling to figure out how to use JavaScript to clear the text in a text box and move it below the box when a user starts typing. I've been watching this tutorial http://codepen.io/ehermanson/pen/KwKWEv ...

RTL in TextInput only functions properly every other time it is rendered

I am facing a strange problem with RTL where everything seems to be flipped correctly except for TextInput, which only works about half of the time. Check out this gif that demonstrates the issue as I switch between English and Hebrew: (click to view a la ...

What is the best way to assign a value to process.env within an npm script?

After creating a new Vue app (using Vite) with npm init vue@latest and selecting Playwright for e2e tests, the configuration file was generated with a field for setting headless mode: const config: PlaywrightTestConfig = { // ... use: { // ... ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

What methods can I use to toggle between different divs using navigation buttons?

There are 4 divs on my webpage that I need to toggle between using the up and down arrows. Despite trying an if else statement, it doesn't work as intended. <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.c ...

Enable automatic full-screen mode on Google Chrome upon page load

I would greatly appreciate it if you could provide an answer to this question, even if it is marked as a duplicate. I have tried various solutions and sought help, but unfortunately, nothing seems to be working for me... What I really need is for the brow ...

The React loader fails to function properly when used with nested routes

I'm currently working on my App.js file where I have defined all the routes for my application. I wanted to implement React-Router data loader functionality. import React from 'react' import { Routes, Route, Navigate, RouterProvider, createB ...

SpineJS combined with Express

Are there any recommended tutorials or case studies showcasing the integration of SpineJS and Express in applications? I have experimented with both technologies, but am currently facing some challenges. My backend is set up to run Express by using coffee ...