Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将数据重置为原始值_Javascript_Vue.js_Vuejs2 - Fatal编程技术网

Javascript 将数据重置为原始值

Javascript 将数据重置为原始值,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,在我的应用程序中,我的数据中有很多属性,当我点击一个按钮时,我需要将数据重置为原始值,因为我在应用程序中操作它们,有没有合适的方法将数据值转换为原始值 data: { showStart: true, isYouAttack: true, valueMonster: 100, valueYou: 100, monsterProgress: 500, youProgress: 500,

在我的应用程序中,我的数据中有很多属性,当我点击一个按钮时,我需要将数据重置为原始值,因为我在应用程序中操作它们,有没有合适的方法将数据值转换为原始值

data: {
        showStart: true,
        isYouAttack: true,
        valueMonster: 100,
        valueYou: 100,
        monsterProgress: 500,
        youProgress: 500,
        alerts: [],
        progressMonster: {
            'width': '500px',
            'backgroundColor': 'green',
            'height': '50px'
        },
        progressYou: {
            'width': '500px',
            'background-color': 'green',
            'height': '50px'
        }
    },

这是我在应用程序中更改的数据,当我单击按钮我想再次获得这些数据时,有没有一种简单的方法可以使用vue.js?

如果需要,可以通过
JSON.parse(JSON.stringify(…)传递vm.$data来获得原始对象的深度克隆
。由提供。代码如下。您可以在创建的回调上定义重置方法。然后调用重置方法,这将触发已更改的属性

可重置组件 试验
thaught vueJS提供了一种简单快速的方法,我尝试了一下
let user = new Vue({
    data: function () {
        return {
            name: 'John',
            address: {
                country: 'China',
                city: 'guangzhou'
            }
        };
    },
    created(){
        let json = JSON.stringify(this.$data);
        this.reset = () => {
            Object.assign(this.$data, JSON.parse(json));
        };
    }
});
test('reset deep copied data & trigger the property changed!', (done) => {
    expect(user.address.city).toEqual('guangzhou');//initialed data

    user.address.city = 'hunan';

    expect(user.address.city).toEqual('hunan');

    user.$watch('address.city', (newValue, oldValue) => {
        expect(newValue).toEqual('guangzhou');
        expect(oldValue).toEqual('hunan');
        done();
    });

    user.reset();//reset methods will trigger property changed.
    expect(user.address.city).toEqual('guangzhou');

});