Gudradain
Gudradain

Reputation: 4753

Resetting data when property of component change

I built a custom component to which I pass a property.

<template id="friend-component">
    <div>
        {{friend}}
        <div style="color:red;">{{error}}</div>
        <br />
        <input type="button" v-on:click="addFriend" />
    </div>
</template>

<script>
    Vue.component('friend', {
        template: '#friend-component',
        props: ['friend'],
        data: function(){
            return { error: '' };
        },
        methods: {
            addFriend: function () {
                //Call server and try to insert in database
                //Details left out for simplification
                this.error = 'You already added this friend';
            }
        }
    });
</script>

<friend :friend="selectedFriend"></friend>

Then, everytime the parent change the "selectedFriend", I want the data in the child component to be deleted. In this case, it means to delete the error message.

How could I do it?

Note: I figured a way to do it by using a property to store the error instead of the data object. But, Vue is constantly reminding me that I should not modify property...

Mutating a prop locally is now considered an anti-pattern, e.g. declaring a prop and then setting this.myProp = 'someOtherValue' in the component. Due to the new rendering mechanism, whenever the parent component re-renders, the child component’s local changes will be overwritten. Source

Upvotes: 0

Views: 2256

Answers (1)

Bert
Bert

Reputation: 82489

With the limited amount of information provided, a watch is probably most appropriate here.

watch:{
  friend(){
    this.error = ""
  }
},

Here is an example.

console.clear()

Vue.component('friend', {
  props: ['friend'],
  template:"#friend-component",
  data: function(){
    return { error: '' };
  },
  watch:{
    friend(newVal){
      this.error = ""
    }
  },
  methods: {
    addFriend: function () {
      this.error = 'You already added this friend';
    }
  }
});
new Vue({
  el: "#app",
  data:{
    selectFriend:"Bob"
  }
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
  <friend :friend="selectFriend"></friend>
  <button @click="selectFriend = 'Mary'">New Friend</button>
</div>

<template id="friend-component">
    <div>
        {{friend}}
        <div style="color:red;">{{error}}</div>
        <br />
        <input type="button" v-on:click="addFriend" value="Add" />
    </div>
</template>

Clicking Add here will show the error. Clicking "New Friend" afterwards will set the parent's value of friend and the watch will fire, clearing the error.

Upvotes: 4

Related Questions