Javascript 是否有在 vuejs 中重置组件初始数据的正确方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35604987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a proper way of resetting a component's initial data in vuejs?
提问by Chris Schmitz
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:
我认为可行的解决方案是在ready
方法中获取初始数据属性,然后使用保存的数据来重置组件:
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.
但是initialDataConfiguration
对象随着数据而变化(这是有道理的,因为在 read 方法中我们initialDataConfiguration
正在获取数据函数的范围。
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?
硬编码初始数据是唯一的选择吗?
回答by Linus Borg
- extract the initial data into a function outside of the component
- use that function to set the initial data in the component
- 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());
}
}
回答by gertas
To reset component data
in a current component instance you can try this:
要重置data
当前组件实例中的组件,您可以尝试以下操作:
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 componentscope. Here is option of the abstract modal which resets data every time the customized modal is shown (ES2015 code):
我私下有抽象模态组件,它利用插槽来填充对话框的各个部分。当自定义模态包装该抽象模态时,槽中引用的数据属于父组件范围。这是抽象模式的选项,每次显示自定义模式时都会重置数据(ES2015 代码):
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.
您当然可以微调您的模态实现 - 上面也可以在某个cancel
钩子中执行。
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.
请记住,$parent
不建议从 child中改变选项,但是我认为如果父组件只是自定义抽象模态而仅此而已,这可能是合理的。
回答by roli roli
Caution,
Object.assign(this.$data, this.$options.data())
does not bind the context into data().
注意,
Object.assign(this.$data, this.$options.data())
不要将上下文绑定到 data() 中。
So use this:
所以使用这个:
Object.assign(this.$data, this.$options.data.apply(this))
Object.assign(this.$data, this.$options.data.apply(this))
cc this answer was originally here
cc 这个答案最初是在这里
回答by srmico
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.
无需弄乱 $data。
回答by Armin
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:
子组件:
- defining data in an outside function,
- assigning the data object to and outside function
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()); },
- 在外部函数中定义数据,
- 将数据对象分配给函数和外部函数
定义由父组件调用的 clearallData() 方法
function initialState() { return { someDataParameters : '', someMoreDataParameters: '' } } export default { data() { return initialState(); }, methods: { clearAllData() { Object.assign(this.$data, initialState()); },