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

Chr*_*itz 68 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
        }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

我认为可行的解决方案是在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我是否过度思考这个问题并且有更好/更简单的方法吗?

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

Lin*_*org 89

  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());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @SankalpSingha Vue 2.0不允许你再这样做了.您可以使用`Object.assign`代替.这是工作代码:http://codepen.io/CodinCat/pen/ameraP?editors = 1010 (27认同)
  • 它现在给出一个错误:`[Vue警告]:避免替换实例根$ data.请改用嵌套数据属性.` (13认同)
  • 这样做了.谢谢!我对答案做了一个小编辑,但只是因为一个vue组件需要为数据而不仅仅是一个对象返回一个函数.你的答案概念肯定有效并且是正确的,编辑只是为了说明vuejs如何处理组件. (4认同)
  • 你对数据属性的功能是正确的,那是我的草率.谢谢你的编辑. (3认同)
  • 对于这个问题 - [Vue警告]:避免替换实例根$ data.请改用嵌套数据属性,试试这个.$ data.propName ="new value"; (3认同)

ger*_*tas 29

要重置data当前组件实例中的组件,您可以尝试这样做:

Object.assign(this.$data, this.$options.data())
Run Code Online (Sandbox Code Playgroud)

私下我有抽象模态组件,利用插槽填充对话框的各个部分.当自定义模态包装抽象模态时,插槽中引用的数据属于父组件范围.以下是抽象模态的选项,每次显示自定义模态时都会重置数据(ES2015代码):

watch: {
    show (value) { // this is prop's watch
      if(value) {
        Object.assign(this.$parent.$data, this.$parent.$options.data())
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以微调你的模态实现 - 上面也可以在一些cancel钩子中执行.

请记住,$parent不推荐使用子项中的选项变异,但我认为如果父组件只是自定义抽象模式而不是其他内容,则可能是合理的.

  • 注意,这不会将上下文绑定到`data`.因此,如果你在`data`方法中使用`this`,你可以应用上下文:`Object.assign(this.$ data,this.$ options.data.apply(this))` (7认同)

rol*_*oli 20

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

所以使用这个:

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

cc这个答案最初是在这里


小智 9

如果您对警告感到恼火,这是一种不同的方法:

const initialData = () => ({})

export default {
  data() {
    return initialData();
  },
  methods: {
    resetData(){
      const data = initialData()
      Object.keys(data).forEach(k => this[k] = data[k])
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

无需弄乱 $data。


Arm*_*min 8

我必须将子组件内的数据重置为原始状态,这对我有用:

父组件,调用子组件的方法:

<button @click="$refs.childComponent.clearAllData()">Clear All</button >
       
<child-component ref='childComponent></child-component>
Run Code Online (Sandbox Code Playgroud)

子组件:

  1. 在外部函数中定义数据,
  2. 通过定义的函数引用数据对象
  3. 定义由父组件调用的clearallData()方法
function initialState() {
  return { 
    someDataParameters : '',
    someMoreDataParameters: ''
  }
}

export default {
   data() {
    return initialState();
  },
methods: {
  clearAllData() {
    Object.assign(this.$data, initialState());
},
Run Code Online (Sandbox Code Playgroud)