我们从组件中的服务文件中获取变量,但应该保持自己的状态



我有两个组件组件A组件B和一个包含所有常量constants.js的服务文件

constants.js文件有一个变量VMWARE_CONFIG

VMWARE_CONFIG: [
{
name: "Production",
selected: false,
year: "1yr",
},
{
name: "Development",
selected: false,
year: "1yr",
}
]

这个变量被导入到组件A组件B并用作进一步数据处理的过滤器

data() {
return {
priceList: null,
search: null,
mappedInstancesheader: Constants.MappedServerInstancesHeaders,
unMappedServersheader: Constants.UnMappedServerInstancesHeaders,
computeDetailsData: null,
aws_migration_config: "all",
slider: { label: "color", val: 25, color: "orange darken-3" },
vmware_config: Constants.VMWARE_CONFIG,
items: [],
}
}

相同的代码在不同的组件中使用

我面临的问题是,如果用户更改组件a上的过滤器,它也反映在组件B上,我想为每个组件的变量保持不同的状态。

我可以做一件事,在每个组件中定义变量但实际上这个数组对象有超过15个对象并且在超过3个组件中使用还有6个其他变量具有类似的用例

您可以使用扩展操作符,如:

data() {
return {
priceList: null,
search: null,
mappedInstancesheader: Constants.MappedServerInstancesHeaders,
unMappedServersheader: Constants.UnMappedServerInstancesHeaders,
computeDetailsData: null,
aws_migration_config: "all",
slider: { label: "color", val: 25, color: "orange darken-3" },
vmware_config: [...Constants.VMWARE_CONFIG]
items: [],
}
}

更多信息,点击这里

问题是:
导入或使用数组时,要引用它在内存中的位置。
因此,当您使用和更改数组时,您更改了存储在内存中的数组,因此无论在何处使用它,它都会更改,因为它是同一个数组。

解决方案是:
在内存中复制数组,即创建另一个数组
在ES6中最简单的方法是扩展操作符。
但是你也可以使用lodash这样的库cloneDeep

最新更新