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

Display a series of messages using an Angular directive

Here is a sample HTML code: <section class="correspondence"> <header> <div class="from">{{ message.from }}</div> <div class="when">{{ message.when }}</div> </header> <div class="content"> { ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

When taking a vertical picture on my iPhone, my Vue component does not function properly

Having trouble with displaying recently uploaded images on a form. If the image is taken from a phone, it may have an exif property that browsers do not handle correctly, causing the picture to appear flipped or sideways. Upside down photo To fix this is ...

What is a way to automatically run a function at specific intervals in PHP, similar to the setTimeout() function in JavaScript?

I have a JavaScript code snippet that looks like this: setTimeout('$.ajaxCall("notification.update", "", "GET");', 1000); Now, I want to execute the following PHP function every 1000 milliseconds, similar to the above JavaScript code: $notific ...

Flickering of image in JavaScript when mouse is hovered over and removed

I recently encountered an issue while attempting to create a mouseover effect that would display a larger image when hovering over a smaller default image. The problem arose when the larger image started flickering uncontrollably upon hover. Check out the ...

Is there a way to modify the log() function to handle multiple arguments?

Recently, I've been utilizing this logger in node.js: // Found on stackoverflow: https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color function logC(text) { console.log('\x1b[36m%s\x1b[0m', text); ...

How can images be resized according to screen resolution without relying on javascript?

Looking to use a large banner image on my website with dimensions of 976X450. How can I make sure that the image stretches to fit higher resolution monitors without using multiple images for different resolutions? ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...

Having trouble with ejs.filters?

I'm having trouble grasping ejs filters and getting them to work correctly: Server.js var ejs = require('ejs'); ejs.filters.example = function() { //placeholder for example }; Routes.js app.get('/home', function(req, res) { ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

The function window.open() is experiencing difficulties when trying to open a file located in a subfolder

As someone who is new to programming, please excuse any lack of knowledge on my part, but I am having trouble finding the answer to this. I am currently using window.open() to open a .php file in a popup window and passing a variable through the URL to be ...

Switch back and forth between two tabs positioned vertically on a webpage without affecting any other elements of the page

I've been tasked with creating two toggle tabs/buttons in a single column on a website where visitors can switch between them without affecting the page's other elements. The goal is to emulate the style of the Personal and Business tabs found on ...

How can I incorporate the "onClick()" function within an ajax call, while still utilizing the data returned in the success message?

After successfully making an Ajax call, I would like to implement an on-click function while still utilizing the original data retrieved. $.ajax({ URL: ......, type: 'GET', success: function (res) { var Ob ...

Passing variables from AJAX response to PHP using a passthru function

In my PHP file, I have implemented a functionality where certain checkboxes are checked and upon clicking a button, a JavaScript file is triggered. The JavaScript code snippet used is as follows: $.ajax ({ type: "POST", url: "decisionExec.php", ...

Alter the Cascading Style Sheets (CSS) value by accessing a

I have two files, keyboard.css and keyboard.js. My objective is to modify a CSS rule: .ui-keyboard div { font-size: 1.1em; } Is there an alternative method to change the font size without utilizing $(".ui-keyboard div").css()? I want the modification ...

A step-by-step guide on making a list item clickable and redirecting to a URL using Vue.js

Utilizing vue.js, I have successfully configured a navigation bar with multiple list elements. However, I am seeking guidance on how to redirect one of the list elements to an external website, such as https://www.google.com/. Within my router file, each e ...

Only trigger the function for a single bootstrap modal out of three on the current page

I'm facing a challenge on a page where I have 3 bootstrap modals and I need to trigger a function only for one modal while excluding the other two. $("body").on("shown.bs.modal", function() { alert('modal Open'); //this alert should ...

I am currently exploring React Router, but I am struggling to grasp this particular behavior

My Express server serves the Create-React-App build. When I access http://localhost:8000/ while the server is listening, my page loads correctly. However, if I reload the page or navigate directly to it from the navigation bar, instead of seeing the UI, pl ...

A Guide to Connecting a JavaScript File to an HTML Page with Express and Node.js

Struggling with integrating my JavaScript file into my simple NodeJS app. Traditional methods like placing the script in the header doesn't seem to work with Node. I've attempted using sendFile and other approaches, but none have been successful ...

Getting a Next.js error after performing a hard refresh on a page that contains a dynamic query

I have encountered an issue with my Next.js app when I attempt to hard reload it in production mode. The error message I receive is 404 - File or directory not found. Below is the code snippet I am using: import { useRouter } from "next/router"; import ...