12

I have a component that is provided an initial data property via a passed-in component prop and stored in a data variable:

<component :propvar="true"></component>

data() {
  return {
    localvar: this.propvar,
    localvar2: true
  }
}

I would like to be able to revert the data variable back to this prop's value when hitting a 'reset' button with a method like this:

methods: {
  reset() {
    Object.assign(this.$data, this.$options.data());
  }
}

The problem is that the data variable is undefined when referencing the prop's value via this.options.data():

console.log(this.$options.data()); => Object {localvar: undefined, localvar2: true}

Example Fiddle

1 Answer 1

21

If you really need to reset all of your data properties by firing the data() method again, you can do that like so:

methods: {
  reset() {
    Object.assign(this.$data, this.$options.data.call(this));
  }
}

The this variable in the this.$options.data is referencing the options, not the vue component instance. That's why the localvar property was undefined. So if you're calling it from the vue instance, you'll need to give it a reference to this via the function's call() method.


But, in most circumstances, I would just assign the value directly instead of calling Object.assign:

methods: {
  reset() {
    this.localvar = this.propvar;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! That seems to do the trick. Just for clarification: the reason why I would prefer to use Object.assign() in this instance is because it is a lot cleaner when you have many props (which I do for this particular component - not shown in the example). Just as you stated, under most circumstances, the other method would be just fine . Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.