145

I have a component with a specific set of starting data:

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

This is data for a modal window, so when it shows I want it to start with this data. If the user cancels from the window I want to reset all of the data to this.

I know I can create a method to reset the data and just manually set all of the data properties back to their original:

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

But this seems really sloppy. It means that if I ever make a change to the component's data properties I'll need to make sure I remember to update the reset method's structure. That's not absolutely horrible since it's a small modular component, but it makes the optimization portion of my brain scream.

The solution that I thought would work would be to grab the initial data properties in a ready method and then use that saved data to reset the components:

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

But the initialDataConfiguration object is changing along with the data (which makes sense because in the read method our initialDataConfiguration is getting the scope of the data function.

Is there a way of grabbing the initial configuration data without inheriting the scope?

Am I overthinking this and there's a better/easier way of doing this?

Is hardcoding the initial data the only option?

Chris Schmitz
  • 20,160
  • 30
  • 81
  • 137
  • Are you using v-show or v-if to display the modal? – Rwd Feb 24 '16 at 14:37
  • I'm using bootstrap for the css so I'm using it's built in modal which leverages jquery for the showing and hiding. So essentially the window portion of the component is always there, just hidden. – Chris Schmitz Feb 24 '16 at 14:41

6 Answers6

191
  1. extract the initial data into a function outside of the component
  2. use that function to set the initial data in the component
  3. re-use that function to reset the state when needed.

// 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());
    }
}
lukas_o
  • 3,776
  • 4
  • 34
  • 50
Linus Borg
  • 23,622
  • 7
  • 63
  • 50
  • 6
    That did it. Thanks! I did a small edit to the answer, but only because a vue component requires a function returned for data instead of just an object. Your answers concept definitely works and is correct, the edit is just to account for how vuejs handles components. – Chris Schmitz Feb 24 '16 at 15:19
  • 4
    You are right about the function for the data property, that was me being sloppy. Thanks for the edit. – Linus Borg Feb 24 '16 at 21:54
  • 13
    It now gives an error : `[Vue warn]: Avoid replacing instance root $data. Use nested data properties instead. ` – Sankalp Singha Oct 31 '16 at 09:09
  • 35
    @SankalpSingha Vue 2.0 doesn't allow you to do that anymore. You can use `Object.assign` instead. Here is the working code: http://codepen.io/CodinCat/pen/ameraP?editors=1010 – CodinCat Nov 02 '16 at 02:25
  • 3
    For this issue - [Vue warn]: Avoid replacing instance root $data. Use nested data properties instead, try this.$data.propName = "new value"; – Stanislav Ostapenko Jul 20 '18 at 07:45
  • It is not mandatory to extract the function that sets initial data though. I personally put this function in my component `methods` and then just call it with `this.` – lbris Mar 05 '20 at 10:33
  • as of vue 2, use @srmico answer below. – Alexander Kim Dec 29 '20 at 17:44
  • @CodinCat that gives error: [Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions. And doesn't work. – geoidesic Apr 19 '22 at 12:36
  • This solution still looks 'sloppy'. When the component loads, isn't correct to get the values set without calling a custom function for `initialState`? – Vitomir Jul 20 '23 at 15:54
51

Caution, Object.assign(this.$data, this.$options.data()) does not bind the context into data().

So use this:

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

cc this answer was originally here

Roland
  • 24,554
  • 4
  • 99
  • 97
47

To reset component data in a current component instance you can try this:

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

Privately I have abstract modal component which utilizes slots to fill various parts of the dialog. When customized modal wraps that abstract modal the data referred in slots belongs to parent component scope. Here is option of the abstract modal which resets data every time the customized modal is shown (ES2015 code):

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

You can fine tune your modal implementation of course - above may be also executed in some cancel hook.

Bear in mind that mutation of $parent options from child is not recommended, however I think it may be justified if parent component is just customizing the abstract modal and nothing more.

gertas
  • 16,869
  • 1
  • 76
  • 58
  • 1
    This technique now gives a VueJS warning; see http://stackoverflow.com/questions/40340561/proper-way-to-re-initialize-the-data-in-vuejs-2-0 – Kivi Shapiro Apr 05 '17 at 21:15
  • 11
    Caution, this does not bind the context into `data`. So if you are using `this` into your `data` method you can apply the context with : `Object.assign(this.$data, this.$options.data.apply(this))` – Ifnot Jun 16 '17 at 10:27
  • What is the advantage of these way versus location.reload()? – Carlos Sep 05 '19 at 22:58
  • 1
    @Carlos `location.reload` fully reloads a webpage, which is not what we usually need when trying to reset an individual's component state. – Eugene Karataev Nov 03 '21 at 03:07
13

If you are annoyed by the warnings, this is a different method:

const initialData = () => ({})

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

No need to mess with $data.

srmico
  • 151
  • 1
  • 4
8

I had to reset the data to original state inside of a child component, this is what worked for me:

Parent component, calling child component's method:

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

Child component:

  1. defining data in an outside function,
  2. referencing data object by the defined function
  3. defining the clearallData() method that is to be called upon by the parent component
function initialState() {
  return { 
    someDataParameters : '',
    someMoreDataParameters: ''
  }
}

export default {
   data() {
    return initialState();
  },
methods: {
  clearAllData() {
    Object.assign(this.$data, initialState());
},
Armin
  • 2,021
  • 2
  • 19
  • 17
3

There are three ways to reset component state:

  1. Define key attribute and change that
  2. Define v-if attribute and switch it to false to unmount the component from DOM and then after nextTick switch it back to true
  3. Reference internal method of component that will do the reset

Personally, I think the first option is the clearest one because you control the component only via Props in a declarative way. You can use destroyed hook to detect when the component got unmount and clear anything you need to.

The only advance of third approach is, you can do a partial state reset, where your method only resets some parts of the state but preserves others.

Here is an example with all the options and how to use them: https://jsbin.com/yutejoreki/edit?html,js,output

Buksy
  • 11,571
  • 9
  • 62
  • 69
  • 1
    defining `:key` solved this for me. Without it, internal state of components - when changing to another component of the same type - is cached and causes weird issues. – Rebs Oct 31 '22 at 07:00