在 vuejs 中是否有重置组件初始数据的正确方法?

2024-01-15

我有一个带有一组特定起始数据的组件:

data: function (){
    return {
        modalBodyDisplay: 'getUserInput', // possible values: 'getUserInput', 'confirmGeocodedValue'
        submitButtonText: 'Lookup', // possible values 'Lookup', 'Yes'
        addressToConfirm: null,
        bestViewedByTheseBounds: null,
        location:{
            name: null,
            address: null,
            position: null
        }
}

这是模式窗口的数据,所以当它显示时我希望它从这些数据开始。如果用户从窗口取消,我想将所有数据重置为此。

我知道我可以创建一种方法来重置数据,只需手动将所有数据属性设置回原始值:

reset: function (){
    this.modalBodyDisplay = 'getUserInput';
    this.submitButtonText = 'Lookup';
    this.addressToConfirm = null;
    this.bestViewedByTheseBounds = null;
    this.location = {
        name: null,
        address: null,
        position: null
    };
}

但这看起来确实很马虎。这意味着如果我对组件的数据属性进行更改,我需要确保记得更新重置方法的结构。这并不是绝对可怕的,因为它是一个小的模块化组件,但它让我大脑的优化部分尖叫。

我认为可行的解决方案是获取初始数据属性ready方法,然后使用保存的数据重置组件:

data: function (){
    return {
        modalBodyDisplay: 'getUserInput', 
        submitButtonText: 'Lookup', 
        addressToConfirm: null,
        bestViewedByTheseBounds: null,
        location:{
            name: null,
            address: null,
            position: null
        },
        // new property for holding the initial component configuration
        initialDataConfiguration: null
    }
},
ready: function (){
    // grabbing this here so that we can reset the data when we close the window.
    this.initialDataConfiguration = this.$data;
},
methods:{
    resetWindow: function (){
        // set the data for the component back to the original configuration
        this.$data = this.initialDataConfiguration;
    }
}

But the initialDataConfiguration对象随着数据而变化(这是有道理的,因为在 read 方法中我们initialDataConfiguration正在获取数据函数的范围。

有没有一种方法可以在不继承范围的情况下获取初始配置数据?

我是否想得太多了,有更好/更简单的方法吗?

硬编码初始数据是唯一的选择吗?


  1. 将初始数据提取到组件外部的函数中
  2. 使用该函数设置组件中的初始数据
  3. 需要时重新使用该函数来重置状态。
// 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());
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 vuejs 中是否有重置组件初始数据的正确方法? 的相关文章

随机推荐