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

后端 未结 5 1374
遥遥无期
遥遥无期 2020-11-29 18:07

I have a component with a specific set of starting data:

data: function (){
    return {
        modalBodyDisplay: \'getUserInput\', // possible values: \'ge         


        
5条回答
  •  情深已故
    2020-11-29 18:41

    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.

提交回复
热议问题