Mohamed Mamdoh
Mohamed Mamdoh

Reputation: 61

How can I change the value of props in vue with a method in a component?

iam practising vuejs transfering data between components and this is my code

My blade template:

  `<app-user-details :name="name"></app-user-details>`

Then in my Child-Component:

<template>
   <div>
       <h4>You may view the user details here</h4>
       <p>Many Details</p>
       <p>User name: {{ name }}</p>
       <button @click="resetName">reset name</button>
   </div>
</template>

<script>
export default {
   name: 'app-user-datails',
   props: {
       name: {
           type: String
       }
   },
   methods: {
       resetName() {
        return  this.name = 'Max'
       }
   }
}
</script>

i want to change the name in props by the method resetName() but in the console i get this error

vue.js:1355 Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'name'

what should i do?!

Upvotes: 6

Views: 7503

Answers (1)

jcoleau
jcoleau

Reputation: 1200

You should not try to update a prop for inside a child component, from the docs :

All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent’s state, which can make your app’s data flow harder to understand.

However, you can emit an event with the new name from the child component :

  resetName() {
   this.$emit('updateName', 'Max')
  }

And update it from the parent by listening to the event:

 <app-user-details :name="name" @updateName="name = $event"></app-user-details>

Upvotes: 6

Related Questions