vue.js 重置组件状态

vue2中的数据初始化,一般是这样的:

export  default{
 data(){
 	someObj:{
    	aProperty:"",
    	bProperty:""
    }
 }
}

初始数据在data()函数中,外边拿不到,往往新增后,需要恢复到初始状态,参考Is there a proper way of resetting a component’s initial data in vuejs?可以将初始化数据的代码抽取为外部函数,然后调用

// 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 (){
    //这里可以灵活处置了,如果是某个属性,则可以this.xxx=initialState()
        Object.assign(this.$data, initialState());
    }
}

猜你喜欢

转载自blog.csdn.net/wangjun5159/article/details/129955850
今日推荐