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

新手上路,请多包涵

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

 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;
    }
}

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

有没有办法在不继承范围的情况下获取初始配置数据?

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

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

原文由 Chris Schmitz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 387
2 个回答
  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());
    }
}

原文由 Linus Borg 发布,翻译遵循 CC BY-SA 4.0 许可协议

注意, Object.assign(this.$data, this.$options.data()) 不会将上下文绑定到 data()。

所以使用这个:

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

cc 这个答案原来是 在这里

原文由 Roland 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题