Tips for effectively handling a prop in an HTML form using Vue.js and avoiding infinite loops with a computed property

I have a Vue.js form for signing up that features numerous similar fields. From my understanding, I should initialize the values as props rather than objects or arrays (since they will be pass-by-value).

My approach involves using a computed property with getters and setters. Would it be correct to emit the value to the parent component when setting my computed property? If not, what would be a better way to handle this?

Furthermore (and here's the main concern), if I emit from the setter and catch it in the parent component, wouldn't this potentially create an endless loop as it passes back down as a prop? Or does Vue have some mechanism to prevent re-emitting if the value remains unchanged? In other words, does assigning the same value passed through props trigger a watch-getter to fire?

Consider the hypothetical scenario where the component is defined first and then utilized within another part of the code:

Vue.component('signup-input',{
  props:['placeholder','err','initialValue'],
  template:`
  <label>
    <div class='signup-font'>Company Name Within Component</div>
      <input @focus="err = null" v-model="tmpItem" :placeholder="placeholder" size="30" type="text" v-bind:class="{'no-margin error': err }" />
      <label class="error copy-error" v-if="err">
        {{err}}
      </label>
   </label>
  `,
  computed:{
    tmpItem: {
      get: function(){
        return this.initialValue;
      },
      set: function(newValue){
        console.log('here is newValue: ' + newValue); 
        // Emitting here could lead to an infinite loop?
      }
    }
  },
})


var app7 = new Vue({
  el: '#signup',
  template: `
    <div id="page-bg">
      <signup-input :placeholder="companyName.placeholder" :err="companyName.err" :initialValue="companyName.value"></signup-input>

      <label for="company_name">
        <div class='signup-font'>Company Name</div>
          <input @focus="companyName.err = null" placeholder="My Company" v-model="companyName.value" size="30" type="text" v-bind:class="{'no-margin error': companyName.err }" />
          <label class="error copy-error" v-if="companyName.err">
            {{companyName.err}}
          </label>
       </label>

Answer №1

It seems like you're searching for something along these lines. Check out the documentation for .sync

Vue.component('signup-input',{
  props:['placeholder','err','initialValue'],
  template:`
  <label>
    <div class='signup-font'>Company Name Within Component</div>
      <input @focus="err = null" v-model="localValue" :placeholder="placeholder" 
       @input="$emit('update:initialValue', localValue)"
        size="30" type="text" v-bind:class="{'no-margin error': err }" />
      <label class="error copy-error" v-if="err">
        {{err}}
      </label>
   </label>
  `,
  data() {
    return {
      localValue: this.initialValue
   }
  }
})

var app7 = new Vue({
  el: '#signup',
  template: `
    <div id="page-bg">
      <signup-input :placeholder="companyName.placeholder" :err="companyName.err" :initialValue="companyName.value"></signup-input>

      <label for="company_name">
        <div class='signup-font'>Company Name</div>
          <input @focus="companyName.err = null" placeholder="My Company" v-model.sync="companyName.value" size="30" type="text" v-bind:class="{'no-margin error': companyName.err }" />
          <label class="error copy-error" v-if="companyName.err">
            {{companyName.err}}
          </label>
       </label>

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

What steps can I take to guarantee that a select change event occurs following the setting of ngmodel in Angular2?

I am facing an issue with a select element wherein a basic (change) handler is attached along with an ngmodel. Whenever an <option> with a ng value is set, the change handler triggers before the [(ngModel)] reflects the new values. <div> ...

Having trouble updating the URL path with the $location service in Angular

I'm facing a challenge in updating the URL path using the $location.url service, as it's not reflecting the changes correctly. For instance, my current URL path is http://localhost:64621/module/commercial/#/company/98163780-4fa6-426f-8753-e05a6 ...

Error: Reference 'ref' is undefined in the 'no-undef' context. I am interested in experimenting with loading images from Firebase storage

While working with React, I encountered an issue when trying to fetch an image URL from Firebase Storage and display the image. The error 'ref' is not defined (no-undef) occurred. https://firebase.google.com/docs/storage/web/create-reference Th ...

The component is unable to access VueJS references

Below is a simplified version of the code I am working with: <html> <head> <script src="file:///D:/OtherWork/javascript/vue/vue.js"></script> </head> <body> <div id="app"> & ...

Trouble with window.location functionality following an AJAX request

After a successful response from an AJAX request, the window.location method is not working as expected. However, when I debug step by step in Firefox, the window.location works fine. function login(){ var jason ={"usuario":document.getElementById("inp ...

Exceeded call stack size error when using Vuex and Onboard.js

Currently, I'm facing an issue while attempting to utilize Vuex and Onboard.js for storing a web3 provider in my DApp. Each time I try to commit the selected wallet in my state, I encounter a Maximum call stack size exceeded. Below is how my files are ...

Press the button to eliminate

Is there a way for users to add tags by typing text and then clicking on an add button? Once the tag is added, it appears with a delete button, allowing users to manage their list of tags. The JavaScript code below enables users to add tags successfully, ...

Error when handling JSONP: Unexpected token colon in SyntaxError

Encountering a similar issue to the ones discussed in this JSON Uncaught SyntaxError thread and this JSONP Unexpected Token error thread. I attempted to fetch Divvy data through a JSONP call to avoid using a server for my simple front-end application. $. ...

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

Is it possible to retrieve the values of #select1 and #select2 before initiating the AJAX request?

I am presented with the following snippet of HTML code: <select id="choice1"> <option value="0">Option 0</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3 ...

ajax receives an empty responseText after sending intermediate data to Python on the backend

Initially, the frontend passed an identification to the backend. The backend utilized this identification to retrieve data from the database. The extracted data then underwent additional processing on the backend before being sent back to the frontend. Be ...

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

How can I show a title when redirecting a URL in VUE JS?

My current setup includes a navigation drawer component that changes the title based on the user's route. For example, when navigating to the home page (e.g. "/"), the title updates to "Home", and when navigating to the profile page (e.g. /profile), t ...

Deactivate Mongoose connection in Node.js after completing tasks

Here is a mongoose script I have been using to connect to the local database and perform some operations. However, I am facing an issue with disconnecting the connection after use. const mongoose = require('mongoose'); const db = mongoose.connec ...

Component loader with dynamic rendering for multiple components

Currently, I am in search of a method to dynamically render components within my Angular application. While exploring various options, I came across the concept of dynamic component loading in Angular (refer to https://angular.io/guide/dynamic-component-lo ...

Tips for triggering an error using promise.all in the absence of any returned data?

I'm dealing with an issue in my project where I need to handle errors if the API response returns no data. How can I accomplish this using Promise.all? export const fruitsColor = async () : Promise => { const response = await fetch(`....`); if( ...

Is there a way to optimize Typescript compiler to avoid checking full classes and improve performance?

After experiencing slow Typescript compilation times, I decided to utilize generateTrace from https://github.com/microsoft/TypeScript/pull/40063 The trace revealed that a significant amount of time was spent comparing intricate classes with their subclass ...

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

One way to transfer data from a Vue table component to another Vue table component is by including an edit button on each row in the table. This allows

When working with two table components, one fetching records using axios and the other needing to get records after clicking on the edit button in the parent component, I encountered issues. Despite attempting Vue's parent-to-child component communica ...

Iterate through the loop to add data to the table

Looking for a way to append table data stored in local storage, I attempted to use a loop to add cells while changing the numbers based on row counts. Here is my JavaScript code snippet: $(function() { $("#loadTask").change(function() { var ta ...