我有一个简单的应用程序,其中用户选择从下拉列表中的值,当他们点击“添加”按钮值及其ID应该填充到使用id作为索引的数组。
例:
值
1 - 苹果 3 - 香蕉8 - 梨
用户选择每个水果,单击每个选择后添加。我的阵列应该是这样的:
[
1: Apple,
3: Bananas,
8: Pears
]
不过我最终在Vue公司是这样的:
[
1: Apple,
2: undefined,
3: Bananas,
4: undefined,
5: undefined,
6: undefined,
7: undefined,
8: Pears
]
这些值被作为输入提供给服务器的验证通过,显然这是创建具有数组长度和验证规则的问题。我怎样才能消除这些不确定值或阻止的Vue从首位填充它们?
Vue公司是不是将undefined
到您的阵列。这是JavaScript数组(即sparse arrays)只是行为。
快速溶液,以获得定义的元素的一个新的数组是使用Array.prototype.filter
:
const input = [
'Apple',
undefined,
'Bananas',
undefined,
undefined,
undefined,
undefined,
'Pears'
];
const output = input.filter(x => x); // filter out undefined elements
console.log(output)
数组始终连续的;任何“洞”的阵列中的将充满undefined
。
要改用什么是对象:
{
data() {
return {
items: {}
}
},
methods: {
add(id, item) {
// Vue cannot detect property additions, so we must use
// this method to do so
this.$set(this.items, id, item)
}
}
}
如果你呈现出该物体与v-for
模板的项目,顺序通常是相同的,其中每个项目被添加到该对象(见v-for
with an Object)的顺序。如果您需要的项目在ID顺序渲染,那么你就需要对项目进行排序:
<div v-for="item of itemsArray">{{ item }}</div>
computed: {
itemsArray() {
return Object.entries(this.items)
.sort((a, b) => a[0] - b[0]) // sort entry key (ID)
.map(a => a[1]) // take entry value
}
}