Home » vue » Update Vue Prop inside component [duplicate]

Update Vue Prop inside component [duplicate]

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a Client component that contains a ClientInfo and ClientForm component. Client has a client in its data and passes it to both the form and info as a prop. Inside the ClientForm component I have a method to handle the backend. Now when I try and do this:

axios.put(url, body).then(res => {
  this.client = res.data
})

I get the error message about directly mutating props and how I shouldn’t do it. Now currently I do this:

axios.put(url, body).then(res => {
  Object.keys(res.data).forEach((i) => {
    if(this.client[i] != res.data[i]){
      this.client[i] = res.data[i]
    }
  })
})

Which seems… well kind of sub-optimal.

Is there a better way to handle updating the client object from the ClientForm so that the ClientInfo component gets the new info?

Answers:

You could emit a custom event with the new data:

axios.put(url, body).then(res => {
  this.$emit('client', res.data)
})

…and then react to that event in your Client parent component to update its state:

<ClientForm @client='(data) => client = data' />

I hope this helps.