[Vuejs]-Resetting data when property of component change

4đź‘Ť

âś…

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/vue@2.4.2"></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.

👤Bert

Leave a comment