Vue: Add a function to reset a component's state

Created on 16 Oct 2016  ·  4Comments  ·  Source: vuejs/vue

If there were a function in Vue core to reset a component's state (like this.$reset()), then it will simplify a common pattern and lead to clearer code.

This code

function getInitialData() {
    return {
        a: 1,
        b: 2,
    }
}

export default {
    data: getInitialData,
    methods: {
       reset() {
         this.$data = getInitialData()
       },
       submit() {
         // do stuff
         this.reset()
       }
    }
};

Would become

export default {
    data() {
      return {
        a: 1,
        b: 2,
      }
    }
    methods: {
       submit() {
         // do stuff
         this.$reset()
       }
    }
};
feature request

Most helpful comment

Imo this is very easily done in userland, as @LinusBorg has demonstrated. On the other hand, in practice we might need small variations on how this works, e.g. only reseting part of the data to its original state (like a form object).

Overall I'm against adding such trivial convenience utilities into core - because this opens up a precedence: if A is in core, why isn't B also in there? And if we follow that we end up with an API surface bloated with tiny util functions, which I absolutely don't want to see.

All 4 comments

It might be a nice addition. This is indeed something I find myself doing regularly as well.

Until this might get into core, use this:

Vue.prototype.$reset = function () {
  var data = this.$options.data()
  Object.keys(data).forEach(key => {
    this[key] = data[key]
  })
}

https://jsfiddle.net/Linusborg/4tpzm3e1/1512/

I think this would be super useful, it's something i am forever doing.

Imo this is very easily done in userland, as @LinusBorg has demonstrated. On the other hand, in practice we might need small variations on how this works, e.g. only reseting part of the data to its original state (like a form object).

Overall I'm against adding such trivial convenience utilities into core - because this opens up a precedence: if A is in core, why isn't B also in there? And if we follow that we end up with an API surface bloated with tiny util functions, which I absolutely don't want to see.

Yeah that's a valid concern.

Was this page helpful?
0 / 5 - 0 ratings