Steer clear of changing props directly in VueJS to prevent unintended

I am working with a component that has props, and I need to change the value from false to true. However, I encountered a message in the Chrome console advising against mutating a prop directly because it will be overwritten whenever the parent component re-renders.

Within the parent component, there is a function called myFunction that takes one argument (value).

I want to maintain my argument as is, while also being able to retrieve the emitted value from the child component in order to update myData without directly mutating the props in the child component.

Check out the code here

<template>
  <div>
    <p>The number is {{number}}</p>
    <Child :MyProp="myData" @on-click-btn="myfonction(5)"/>
  </div>

</template>

<script>
import Child from "./components/Child.vue";

export default {
  data() {
    return {
      myData: 'button',
      number: 1
    };
  },
  components: {
    Child
  },
  methods: {
    myfonction(value) {
      this.number = value;
    }
  }
};
</script>

Thank you!

Answer №1

Utilize the sync modifier to achieve this:

Vue.component('child', {
  template: '#child',
  props: {
    val: {
      type: String, required: true
    }
  },
  methods: {
    handleInput(event) {
      this.$emit('update:val', event.target.value)
    }
  }
})

new Vue({
  el: '#app',
  data(){
    return {
      value: ''
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<script type="text/x-template" id="child">
  <input @input="handleInput">
</script>

<div id="app">
  <child :val.sync="value"></child>
  <div>{{ value }}</div>
</div>

Answer №2

Why it's not recommended to directly edit the prop in Vue.js

Instead of modifying the prop directly, a better approach is to use an emit event from the child component and update the parent data that is being passed as the prop. Here's how you can implement this:

Parent Component (parent.vue)

<template>
  <child 
   MyProp="myData"
   @on-click-btn="handleClick" // [2] Listen for the event and attach a handler
  />
</template>

export default {
 data () {
  return {
   myData: false
  }
 },
 // [3] Event handler triggered on user click
 handleClick (currentValue) {
  // [4] Update the passed prop data in parent component so child receives the updated value
  this.myData = !currentValue
 }
}

Child Component (child.vue)

<template>
  <button @click="handleClick">Click me, MyProp is {{ MyProp }}</button>
</template>

export default {
 props: ['MyProp'],
 method: {
  handleClick () {
   // [1] Emit an event on button click with current prop value
   this.$emit('on-click-btn', this.MyProp)
  }
 }
}

Check out the demo here

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

Incorporate JavaScript code into an Angular UI-Router view

I can't seem to find an answer to this question anywhere, so I'm hoping someone here can help me out. In my AngularJS app, I am using ui-router to load multiple views into the same <ui-view> element. I am trying to implement Jquery UI&apos ...

Does the CSV stream parser (PapaParse) cause rendering delays?

Currently, I am utilizing papa parse to fetch csv streams from my backend in order to visualize data. However, I have observed that while it is successfully invoking the callback for the data chunks, it is also causing rendering issues. I am attempting to ...

What steps can be taken to ensure that the getData() function is executed prior to the MovieCard

Struggling to work with async functions while creating a random movie generator app using react js and material ui. It seems like the data retrieval from the API is not quick enough for my component. How can I fix this issue? Is there a way to ensure tha ...

Issue with importing and exporting external types causing failures in Jest unit tests for Vue 2

I am in the process of creating a package that will contain various types, enums, consts, and interfaces that I frequently use across different projects. To achieve this, I have set up a main.ts file where I have consolidated all the exports and specified ...

A guide to effectively unit testing a Vue composition in isolation

In my project, I have organized my code in a similar way to the example in the documentation. This involves keeping my composition logic in a separate file from the component itself. Here is an overview of how it looks: // composition.js import { onMounte ...

You can eliminate the display flex property from the MuiCollapse-wrapper

Having trouble removing the display flex property from the MuiCollapse-wrapper, I did some research and found the rule name for the wrapper in this link https://material-ui.com/api/collapse/ I have been unsuccessful in overwriting the class name wrapper t ...

Is it possible to execute JavaScript in VSCode without the need for Node.js?

Is there a way to run JavaScript in VSCode using a school-issued laptop that does not allow the download of Node.js? I have searched for alternatives, but most tutorials recommend downloading Node.js. ...

When importing modules in node.js, the presence of a function can overwrite another function even if it

Within this code snippet, I am utilizing Express.js. //index.js app.use('/',routes()); //app/routes.js module.exports = function() { express = require('express'); const loggedUserProfileController = require('../controller ...

Using Laravel to remove data with an incorrect ID

Whenever I try to delete data using the Delete button, it seems like the data being deleted does not correspond to the rows I intended. Instead, the data at the top of the table gets deleted. For example, when I use return $meja, id 1 shows up instead of ...

Whenever attempting to detach(), I am encountering the following error message: local.ERROR: Call to a member function programs() on an integer

I am dealing with a Many to Many relationship between Courses and Programs. The insertion of new courses and adding multiple programs works correctly. However, the issue arises during updates. When I update a course, I want to detach all related programs a ...

Issue with generating random cells in a table using a loop

Within my HTML code, I have a table constructed using the table element. To achieve the goal of randomly selecting specific cells from this table, I implemented a JavaScript function that utilizes a for loop for iteration purposes. Despite setting the loop ...

The Vue Loader is unable to resolve images within third party CSS files located in the node modules directory

While using webpack to compile my vue.js application, I encountered an issue when importing a node_module css file that contained images. The images could not be resolved properly. <style lang="less"> @import '~@vue/vue'; </style> ...

data in Vue not updating after setting value in session storage

I recently encountered an issue with setting values to session storage in my main.ts file after making an axios call. Despite successfully saving the data, I found that accessing it in another component resulted in 'undefined' values. It seems li ...

What is the best way to dynamically load a personalized JavaScript file for individual users depending on their PHP login credentials?

Currently, I am conducting a web-based experiment in which students log into a website to take practice tests for a class. Initially, the students land on a login page that includes the following code: include_once("core/config.php"); include_once("core/ ...

Tips for integrating a vue plugin into your nuxt project

I've come across a plugin called vue-chat-scroll and I'm interested in utilizing it within nuxt. As a beginner, I'm not fully grasping how to go about this. I am curious if it's feasible to integrate this Vue plugin into nuxt as a plugi ...

Effortlessly refresh a data object in Vue.js without relying on a function

I need assistance with the following: <Checkbox label="View" :initialState="data.something" @updateStatus="updateCheckbox" > </Checkbox> The variable data.something is a b ...

Dividing a select option

Looking to transform a single select element into multiple select elements using the separator "/" Here is an example of the original code: <select> <option value="1234">Type 1 / Black</option> <option value="5678">Type 2 / White& ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

How to define a different initial route using ui-router in AngularJS?

Is there a way to set a startup route for ui-router that differs from using $urlRouterProvider.otherwise()? Or is it possible to cleverly guide ui-router towards navigating to a different path upon initialization? ...

Ways to transfer a button click event to a callback function

Fiddle: http://jsfiddle.net/cmw0s2rk/ function HandleTopNavClick($elem, pretext = "", replace = false, e) { debugger; e.preventDefault(); var href = $elem.href; } $("ul.check-it li a").on("click", HandleTopNavClick($(this), "clickhere_", true, even ...