Modifying properties within child components

Within my parent Vue Page, I have inserted a FormInput component inside my form.

new.vue

<b-form @submit.prevent="submit">
   <FormInput :name="name"/>
   <b-button @click="submit">Save</b-button>
<b-form>

<script>
 import FormInput from '~/components/Insiders/FormInput';
 export default {
   components: {
    FormInput
   },  
   data() {
     return {
      name: 'User A'
     }
   },
   methods:  {
     submit(event) {
      console.log(this.name)
     }
   }
 }
</script>

components/Insiders/FormInput.vue

<b-form-input v-model="name" type="text"></b-form-input>  
<script>
export default {
  props:   {
    name: { type: String, required: true }
  }
}
</script>

I am encountering an error: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "name"

My expectation is that when I modify the input value in new.vue, I should be able to log the new value of name upon clicking the submit button.

How can this issue be addressed?

Answer №1

To ensure optimal functionality for your component FormInput in this scenario, it is crucial to implement support for v-model.

When creating a user input component, it is important that the component accepts input via props and makes its value available. This can be easily achieved by utilizing v-model, which allows both input and output configurations with a single attribute.

For more information, you can refer to the following articles:

https://alligator.io/vuejs/add-v-model-support/

https://scotch.io/tutorials/add-v-model-support-to-custom-vuejs-component

Edit:

Utilizing the v-model approach simplifies the usage of the FormInput component in New.vue:

<b-form @submit.prevent="submit">
   <FormInput :v-model="name"/>
   <b-button @click="submit">Save</b-button>
<b-form>

<script>
 import FormInput from '~/components/Insiders/FormInput';
 export default {
   components: {
    FormInput
   },  
   data() {
     return {
      name: 'User A'
     }
   },
   methods:  {
     submit(event) {
      console.log(this.name)
     }
   }
 }
</script>

However, the FormInput component still requires additional steps to prevent mutation of the actual input:

<b-form-input :value="value" @input='updateVal' type="text"></b-form-input>  
<script>
export default {
  props:   {
    value: { type: String, required: true }
  },
  methods: {
      updateVal: function(val){
           this.$emit('input', val);
      }
  }
}
</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

error 404 when sending a xhr request in node and react js

I am currently developing a basic login page in React that needs to connect to a database through an AJAX call to a Node.js file. Here is the Node.js code I have implemented: var express=require('express'); var app=express(); var db=require(&ap ...

performing an AJAX call utilizing both a file and post data

I'm reaching out for help because I'm having trouble sending an ajax request with a data file and two posts included Here is the code snippet: $('#image--1').change(function (e) { e.preventDefault(); var img = new FormData(); ...

"Handling API Calls with AngularJS: Dealing with the [object object] Response

Looking for some guidance on pulling a list of articles from the NPR API. I have a functioning URL that returns JSON data. However, in my controller code, I seem to be having trouble accessing the object. When I use console.log to check, it just shows [obj ...

The JSON.stringify() function helps to convert data into a JSON-formatted string, avoiding any potential "c

connection.query( 'SELECT DeskName FROM desks WHERE stat = ?',["Booked"], function(err, rows){ if(err) { throw err; }else{ try{ var dataToParse = new Array(); dataToParse = rows; res.render('workspaces.html',{parsedArray : JS ...

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

Validating Laravel emails with JavaScript blur and utilizing AJAX and jQuery

Looking for a way to validate a form in Laravel without hitting the submit button? I've tried some code, but only the email format validation seems to be working. Any tips on what I should do next? I'm new to Ajax. PS: When I enter a valid email ...

What is the best way to implement forwardRef in a distinct select component?

Currently, I am utilizing react, typescript, and styled-components to work on my project. Specifically, I am aiming to create a select component for use in React Hook Form. Initially, everything seemed to be in order, but I encountered an error from typesc ...

Compatibility issues with jQuery observed in Firefox and Internet Explorer 11

Check out the code here: jsfiddle demo HTML CODE: <div class="first"> <!-- Part one --> <div class="acord_col"> <div class="img_class" id="exist_site"></div> <div class="intro_text"> </div> </div&g ...

Guide to using JavaScript to multiply the values from two text fields and showing the result in a separate text field

Here is the code that I am currently using: <script type="text/javascript"> $(function() { $("#addAll2").click(function() { var add = 0; $("#discount") = $dis $(".amt2").each(function() { ...

Splitting the div into two columns

I've encountered various solutions to this issue, but when I integrate an Angular2 component inside the divs, it fails to function properly. Here is my progress so far: https://i.stack.imgur.com/qJ8a9.jpg Code: <div id="container"> <div ...

Implementing a method to allocate rewards to individual players within a game Bank using arrays in Node.js and JavaScript

In my interactive game, players can choose between two sides to place their bets. At the end of the game, there will be one side declared as the winner and those who placed winning bets will receive a portion of what they wagered. However, I am facing an i ...

Use the Google Maps API to dynamically add a marker via AJAX once the map has been initialized

Although I have come across similar questions with related titles, none of the answers quite fit my needs. Here is the problem I am facing: I'm working on printing a map that contains multiple markers generated from a database. Below the map, there ...

jsonwebtoken does not fetch a token

I've been working on a user registration system using nodejs and sequelize. So far, I've successfully implemented the login and register functionalities. However, I am encountering an issue with getting the token after a successful login. Despit ...

JavaScript or jQuery for filtering table rows

I have limited experience with JavaScript and jQuery, but I am working with a table containing various entries. My goal is to implement a filtering system using a list on the left side of the table. Here is an example I put together: http://jsfiddle.net/B ...

The URL in a request is altered prior to execution

I am encountering an issue with my NodeJS application where it automatically appends my domain to the URL set in my http request. How can I prevent this from happening? I have tried to search for similar problems but have not found any relevant solutions. ...

When running the command `npm install <node_module> --save`, the dependencies are not being updated as

<=== If you're facing the same issue, try reinstalling your computer to fix it ===> I recently had to reformat my computer and set everything up again. After reinstalling Node and NPM, I encountered some problems that are really irritating me. ...

Implementing watch functionality with array in Vuejs for bidirectional communication between parent and child components

Here is a simplified version of a parent component I created: // parent component <template> <layout v-for="(value, idx) in array" :pickUpLength="array.length" :idx="idx" :key="idx" > <button @click="addArray">a ...

Bootstrap 4: In collapsed navbar, li items are shown horizontally beside navbar-brand

I've been troubleshooting this issue for hours. It seems like the navbar is not collapsing correctly in Bootstrap 4, causing the next list item to display to the right of the navbar-brand text instead of below it like the other items. <nav class=" ...

Inserting a new key-value pair into each object within an array

I have a collection of items that I need to add a specific key to in AngularJS using $scope. The following code shows the initial objects: $scope.Items = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sw ...

Determine if the JSON lacks an array within it

Utilizing an API to fetch results, the response received looks something like the following: {"currentPage":1,"numberOfPages":1,"totalResults":1,"data":[{"id":"Sf8xxo","name":"The Bear Reader Huckleberry Oatmeal Stout","nameDisplay":"The Bear Reader Huckl ...