Is there a proper way of resetting a component's initial data in vuejs?

  1. extract the initial data into a function outside of the component
  2. use that function to set the initial data in the component
  3. re-use that function to reset the state when needed.

// outside of the component:
function initialState (){
  return {
    modalBodyDisplay: 'getUserInput', 
    submitButtonText: 'Lookup', 
    addressToConfirm: null,
    bestViewedByTheseBounds: null,
    location:{
      name: null,
      address: null,
      position: null
    }
  }
}

//inside of the component:
data: function (){
    return initialState();
} 


methods:{
    resetWindow: function (){
        Object.assign(this.$data, initialState());
    }
}


To reset component data in a current component instance you can try this:

Object.assign(this.$data, this.$options.data())

Privately I have abstract modal component which utilizes slots to fill various parts of the dialog. When customized modal wraps that abstract modal the data referred in slots belongs to parent component scope. Here is option of the abstract modal which resets data every time the customized modal is shown (ES2015 code):

watch: {
    show (value) { // this is prop's watch
      if(value) {
        Object.assign(this.$parent.$data, this.$parent.$options.data())
      }
    }
}

You can fine tune your modal implementation of course - above may be also executed in some cancel hook.

Bear in mind that mutation of $parent options from child is not recommended, however I think it may be justified if parent component is just customizing the abstract modal and nothing more.


Caution, Object.assign(this.$data, this.$options.data()) does not bind the context into data().

So use this:

Object.assign(this.$data, this.$options.data.apply(this))

cc this answer was originally here