在VueJs 2.0中重新初始化数据的正确方法

JavaScript

卡卡西Near

2020-03-12

我在SO上经历了这个答案:是否有正确的方法在vuejs中重置组件的初始数据?

但是,当前不允许使用当前方法,并且VueJS禁止更改$ data var。

如您在此https://github.com/vuejs/vue/issues/2873所见(不允许修改$ data。)

因此,如果尝试上述方法,则会收到VueJS警告:

[Vue警告]:避免替换实例根$ data。请改用嵌套数据属性。

这是我的JS代码,

function initialState () {
        return {
            h2: 0,
            ch4: 0,
            c2h6: 0,
            c2h4: 0,
            c2h2: 0,
            c3h8: 0,
            c3h6: 0,
            co: 0,
            co2: 0,
            o2: 0,
            n2: 0,
            selected: ''
        }
    }
    export default {
        name: 'something',
        data () {
            return initialState() // This is working fine 
        },
        computed: {
            tdcg: function () {
                // some logic here...
            }
        },
        methods: {
            resetFields: function () {
                this.$data = initialState() // --> This is what I want to achieve!
            }
        }
    }

那么重新初始化数据的正确和最简单的方法是什么?

第1185篇《在VueJs 2.0中重新初始化数据的正确方法》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
LEY神无 2020.03.12

您可以尝试以下方法:

  1. 使用必填字段初始化表单数据属性。(如步骤1所示)
  2. 创建另一个数据字段,该数据字段将用于克隆要重置的表单数据(如STEP 2所示)。
  3. 克隆所需的表单数据(步骤3)
  4. 编写您的重置方法(步骤4)
  5. 在您喜欢的任何地方使用(步骤5)

export default {
  // Initialize your data
  data() {
    return {
      // Initialize the form field (STEP 1)
      formFields: {
        name: '',
        email: '',
        password: '',
        moreData: {
          field1: '',
          field2: [],
        },
      },
      // Create an object property used for cloning (STEP 2)
      formFieldsCopy: {},
    };
  },

  // When the DOM is mounted copy the
  // formField you want to a temporary field
  // You can use lodash ._clone or ES6 spread operator (STEP 3)
  mounted() {
    this.formFieldsCopy = { ...this.formFields
    };
  },
  methods: {
    // Write the function to reset the form (STEP 4)
    resetFormFields() {
      this.formFields = { ...this.formFieldsCopy
      };
    },
    submit() {
      // Do you normal Axios requests here
      // and call you reset function. (STEP 5).
      this.resetFormFields();
    },
  },
};

前端逆天 2020.03.12

您可以Object.assign用来遍历所有属性并分配它们:

export default {
    data () {
        return {
            h2: 0,
            // other attributes...
        };
    },
    methods: {
        resetFields () {
            Object.assign(this.$data, this.$options.data.call(this));
        }
    }
}

这是一个演示小提琴:https : //jsfiddle.net/797yyvtz/


注意:this.$options.data用来data再次调用原始方法来获取数据的新副本。无需单独的initialState功能。data方法初始状态函数。

JinJin乐 2020.03.12

我的解决方案:

mounted(){
    this.saveData() // you can load if you need previous data
},
methods: {
    saveData(){
        localStorage.setItem(this.$options.name,JSON.stringify(this.$data));
    },
    loadData(){
        if (localStorage.getItem(this.$options.name) !== null) {
            let data= JSON.parse(localStorage.getItem(this.$options.name));
            Object.keys(data).forEach((key)=>{this[key] = data[key];});
        }
    }
}

需要时可以再次加载或保存它们

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android