最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Resetting VueJS data properties to initial values - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited Apr 26, 2017 at 20:31 thanksd 55.6k23 gold badges165 silver badges154 bronze badges asked Apr 26, 2017 at 19:49 StetzonStetzon 7392 gold badges10 silver badges19 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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;
  }
}
发布评论

评论列表(0)

  1. 暂无评论