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

标签 javascript mvvm vue.js

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

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 对象随数据一起变化(这是有道理的,因为在 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());
    }
}

关于javascript - 在 vuejs 中是否有重置组件初始数据的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35604987/

相关文章:

laravel - vee-validate 中的自定义验证消息

javascript - 使用 Google Apps 脚本根据 Google 表格中的值禁用日期选择器中的日期

javascript - 带有 WebSocket 的 typescript

javascript - 如何将文本与居中文本的左侧对齐?

javascript - 在选项卡面板中固定选项卡

c# - WPF 应用程序中的后台线程和 UI 线程

WPF 仅数字文本框 - 使用事件或命令处理它?

c# - DataContext 在事件期间间歇性为 null

laravel - 如何在 Laravel + Vue 中隐藏空查询的结果?

javascript - 根据选择显示项目