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

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

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

我认为可行的解决方案是在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得到的是数据函数的范围).

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

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

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

推荐答案

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

Vue.js相关问答推荐

Visual Studio代码中的VUE/VLAR扩展不断崩溃:JS/TS语言服务立即崩溃5次…

使用项目和字段,列跨度为 2 的 Bootstrap-vue 表

如何在Vue3中使用vuechartjs 5.2从父组件更新图表

无法在cPanel/SSH上构建 | Laravel + Vue优化

从数据库中删除后,Vue.js $remove 不删除元素

即使响应为 200,也会调用 Axios Catch

使用 Vue Router 设置页面标题

vuejs中watch方法和计算方法有什么区别

Vue.js 中 Chrome 和 Datalist 的性能问题

如何使表格行可点击并展开行 - vue.js - element-ui

如何使用 vuex 删除项目?

验证子组件Vue vee-validate

数据更新后触发 Vue.js 事件

如何使用 Vuejs 和 Laravel 获取当前经过身份验证的用户 ID?

如何禁用 nuxt 默认错误重定向

'不提供名为'createRouter'的导出'' vue 3、vite 和 vue-router

组件已注册但未使用 vue/no-unused-components

Vue中的嵌套循环

仅在提交时验证 vuetify 文本字段

如何在 Vue.js 2 应用程序中模拟 onbeforeunload?