Reset vue input fields after triggering event

I'm facing an issue with my Vue component that has an input and a button. I want the button to send the input data elsewhere and then clear the input field, but it's not working as expected.

Below is a basic runnable version of what I currently have:

new Vue({
el: '#root',
template: `
<div>
  <input type='text' v-model='name'/>
  <button @click='onClickMe'>Click me</button>
 </div>
`,
  methods: {
    onClickMe () {
     this.$emit('set-this-elsewhere', { name: this.name })
     this.name = ''
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root">
</div>

Answer №1

Do you notice the error appearing in the console?

The property or method "name" is being referenced during rendering but has not been defined on the instance

To resolve this, you must include the following code:

data() { 
  return {
    name:''
  }; 
},

new Vue({
  el: '#root',
  template: `
<div>
  <input type='text' v-model='name'/>
  <button @click='onClickMe'>Click me</button>
 </div>
`,
  data() {
    return {
      name: ''
    };
  },
  methods: {
    onClickMe() {
      this.$emit('set-this-elsewhere', {
        name: this.name
      })
      this.name = ''
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root">
</div>

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

Retrieve both the keys and values from a deeply nested JSON object

My goal is to retrieve JSON data with a specific structure as shown below: {"Points": {"90": {"0": {"name": "John Phillip", "slug": "john"}, {"1&q ...

Using Django and Vue.js to implement JSON Web Token (JWT) authentication

I am looking to establish a public space on a website with the utilization of standard Django and templates. Once a user logs into the members area, they will be automatically logged into a single page application (SPA) built using Vue.js and Django Rest F ...

Show the template when the link is clicked using Angular directive

Perhaps the question is not phrased properly, but here is the idea I am working on. I have a navbar set up with an array of countries that includes their names and coordinates. <body> <nav class="navbar navbar-default"> <div cl ...

Sending variables to other parts of the application within stateless functional components

My main component is Productos and I also have a child component called EditarProductos. My goal is to pass the producto.id value from Productos to EditarProductos. Here is my Productos component code: import {Button, TableHead, TableRow, TableCell, Tabl ...

Ensure to wait for the user ID before accessing Firestore collections

Trying to wrap my head around rxJs and experimenting with using the where query in Firestore collection. However, I've run into an issue where the output of this collection is dependent on retrieving the user ID from Firebase Auth. Here's what I ...

Protected node.js REST API

I want to ensure the security of a restful API and aim to keep it simple and stateless. What is the best way to store, generate, and authenticate API keys? I was considering using node-uuid to generate keys, storing them in Redis, and then authenticating ...

Animating a mesh in three.js with color transitioning using tween.js

I've been struggling to accomplish this task. My goal is to change the color of a ConvexGeometry mesh when hovered over. So far, I can successfully change the mesh's color without any issues. The problem arises when I attempt to create a smooth ...

Retrieve JSON data generated within a JavaScript-powered webpage

My issue involves two HTML pages: 1) The first HTML Page (page1.html): <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script> <script type="text/ ...

Disable audio playback on tab unfocus using Javascript/HTML

Is there a way to automatically mute a tab or video when it is not in focus? As a beginner, I am unsure how to accomplish this task. The audio source is currently a webm file embedded within a <video> tag. ...

The Vuetify table encounters a loading error when trying to retrieve data

Encountering an error with the following code 'Property "item" was accessed during render but is not defined on instance'. However, when I switch it to a normal everything functions properly. <!DOCTYPE html> <html lang="e ...

Data of an object disappears when it is passed to Meteor.call

In my React/Meteor project, I encountered an issue while trying to pass an object with data from the state to a method on the server for database insertion. Surprisingly, when the object is passed from the React component to the Meteor method, one of the c ...

Running complex operations within a sorting function just once

I am facing the challenge of sorting an array of objects based on multiple date fields, with the added complexity of excluding certain dates depending on the category. In order to optimize performance, I want to minimize the number of times the getUsefulJo ...

There seems to be a glitch preventing Highchart from functioning within a jQuery function

Hello there! I'm currently utilizing the highchart API to generate graphs in a loop. for(i=1;i<10;i++) { xseries = "{'INCOPAV','B&M','SGS-ETSA'}"; yseries = "[{name: &apos ...

Issues with HTTPS in Puppeteer and VUE JS

I am encountering an issue when running tests from NODE net::ERR_CONNECTION_REFUSED at https://localhost:8087 at navigate (node_modules/puppeteer/src/common/FrameManager.ts:190:13) Test Suites: 2 failed, 2 total Tests: 7 failed, 7 total Snapshots: ...

I recently started delving into React Native and am currently exploring how to implement custom fonts in my application. However, I have encountered an error that is preventing me from successfully integrating

The Issue: The error I encountered only appeared after including font-related code (such as importing from "expo-font" and using "AppLoading" from "expo", and utilizing the "Font.loadAsync()" function). Error: Element type is invalid: expected a string (fo ...

Make sure to include a space before each character when entering text in TinyMCE

I am interested in creating a MS-Word-like system for managing non-breaking spaces before certain characters: My goal is to automatically insert a non-breaking space before characters like ?, !, :, etc. while typing (or replace a normal space with a non-b ...

Am I on the right track with my service definition in Angular?

(function(){ angular.module('myApp',[]) })(); (function(){ angular.module('myApp.dashboard',[]) })(); (function(){ angular.module('myApp.value',[]) })(); (function(){ 'use strict'; angular.modu ...

Is there a way for me to acquire more information on event bubbling in web development, specifically relating to the YUI framework?

Are there any recommended resources for learning about event bubbling, specifically within the context of the Yahoo User Interface libraries (YUI)? ...

Error Encountered: Duplicate Key Found in Repeater while using an Array called 'name'. The issue is resolved when using a different name

Here's the issue: when the variable is named 'name', the error 'dupes Duplicate Key in Repeater' appears! But why does this happen? Here's the code snippet: app.js var galleryModule = angular.module ("gallery",[]); var name ...

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...