Javascript/Vue
重置data
在 Vue 中,如果你想还原 data 中的数据为初始值,常见做法是:
方法一:使用一个初始数据拷贝
export default {
data() {
return {
formData: {
name: '',
age: ''
},
initialData: null
};
},
created() {
// 保存初始值的深拷贝
this.initialData = JSON.parse(JSON.stringify(this.formData));
},
methods: {
resetForm() {
this.formData = JSON.parse(JSON.stringify(this.initialData));
}
}
}方法二:封装 data 函数并调用初始化
export default {
data() {
return this.getInitialData();
},
methods: {
getInitialData() {
return {
name: '',
age: ''
};
},
reset() {
Object.assign(this.$data, this.getInitialData());
}
}
}方法三:使用 this.$options.data()
这是一种非常优雅的方式,直接利用 Vue 实例的 $options 属性:
export default {
data() {
return {
form: {
name: '',
age: 0,
email: ''
}
}
},
methods: {
resetData() {
// 通过调用原始的 data 函数获取初始值
Object.assign(this.$data, this.$options.data())
}
}
}