所以我有一个 vue 组件用作编辑界面...
数据库里面有一个 jsonified 数组(不要问...我也不喜欢它),它必须采用特定的格式...为了允许管理员编辑这个字符串数组而不破坏格式,我正在制作一个 vue 编辑组件,它将把各个部分分解成各种文本框等......
我想要两个单独的变量 - 一个用于字符串数组的内容,另一个用于它们正在更改的内容...第一个变量将在保存更改时更新...
我遇到的问题是,由于某种原因,当我更新其中一个变量时...不仅另一个变量发生变化...而且 prop 也会发生变化...
我的印象是组件无法更改其 props..?
特别是,该数组看起来像这样:
[
'1',
'2'
['1','2','3','4']
]
当我执行 .splice()
时在子数组上,变量和属性都会更新...
一些示例代码...
Laravel Blade View :
<editor :somearray={{ $someJsonifiedArray }}></editor>
组件 Prop /数据设置:
props: {
somearray: {
default: [],
type: Array
}
}
data(){
return {
editedArray: this.somearray, // This is what will be saved
wipArray: this.somearray // This is what changes as they edit
}
}
一些方法:
resetChanges(){
this.wipArray = this.editedArray;
}
我可能错过了一些明显的东西......或者误解了事情的运作方式......
最佳答案
Javascript Array/Object is passed by reference, not by value!
如果你这样做
return {
editedArray: this.somearray, // This is what will be saved
wipArray: this.somearray // This is what changes as they edit
}
每当您编辑 editedArray
或 wipArray
时,您实际上是在编辑 somearray
,因为它们都引用同一个数组/对象。
所以你必须克隆数组/对象而不是直接传递它。克隆对象的最简单方法是使用 spread operator (或者在某些情况下,需要deep cloning)。克隆数组的最简单方法是使用 slice .
return {
editedArray: {...this.somearray}, // This is what will be saved
wipArray: {...this.somearray} // This is what changes as they edit
}
关于javascript - Vue2 组件以某种方式修改 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49067202/