我认为 ES6 模块导出总是不可变的,所以我对我得到的行为很困惑。我有一个简单的颜色数组,我想在我的 Vue 应用程序的多个组件中使用它们。它在它自己的文件中,如下所示:
export const colors = [
'#ffb3ba',
'#ffdfba',
'#ffffba',
'#bae1ff',
]
然后我将它导入到我想要使用它的组件中,如下所示:
import { colors } from '../assets/colors';
我有一个功能,可以随机选择一种颜色,然后将其从列表中删除,这样就不会为同一组件再次选择它。是这样的。
descriptions.forEach(item => {
const colorIndex = Math.floor(Math.random() * colors.length);
item['color'] = colors[colorIndex];
colors.splice(colorIndex, 1);
});
这里的想法是从列表中随机选择一种颜色,为其分配描述,然后将其从列表中删除,以便在 forEach
的下一次迭代中选择不同的颜色。 .
问题是它似乎要从列表中永久删除颜色。因此,当我导入并尝试在另一个组件中使用该数组时,其中没有颜色。我怎样才能让它有一个新的 colors
实例?每个组件的数组?
最佳答案
导入的绑定(bind) 是不可分配的,仅此而已。它们类似于 const
- 您不能更改变量 but you can mutate the object it holds .为防止出现这种情况,请在导出时卡住对象:
export const colors = Object.freeze([
'#ffb3ba',
'#ffdfba',
'#ffffba',
'#bae1ff',
]);
How can I make it so there is a fresh instance of the
colors
array for every component?
看看Copying array by value in JavaScript为此:只需 colors.slice()
。你也想看看How to randomize (shuffle) a JavaScript array?如何有效地为您的描述获取随机颜色 - 甚至有 some answers不会改变输入。
import { colors } from '../assets/colors';
import { shuffle } from '…';
const randomColors = shuffle(colors.slice());
console.assert(descriptions.length <= randomColors.length);
for (const [i, description] of descriptions.entries())
description.color = randomColors[i];
关于ecmascript-6 - ES6 模块不变性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510504/