如果预定义对象没有数据,如何添加数据?



如果要删除数据,我找到具有findinindex的元素,并将其作为isInArray中的空值丢弃。如果没有这样的数据,如何将其添加到从第一个元素开始的空元素中?例如,如果第一个数据中的元素是满的,它应该知道第二个元素是空的,并将其添加到第二个元素中。

<template>
<input type="text" v-model="name">
<input type="text" v-model="surname">
<button @click="addCustomer"></button>
</template>
<script>
import Vue from "vue";
export default {
data(){
return{
name:null,
surname:null,
customers:[{},{},{}],
currentIndex:null
}
},
methods:{
addCustomer(){
let findIndex = this.customers.findIndex((customer) => customer.name === this.name );
let isInArray = findIndex !== -1;
if(isInArray){
Vue.set(this,"currentIndex",findIndex)
Vue.set(this.customers[this.currentIndex], 'name', null)
}else{
// What Should I write here?
}
}
}
}
</script>

从你的问题中理解,如果你想添加客户到列表中,如果没有客户的名字,如果存在,那么从列表中更新现有的客户。

那么你的代码应该是这样的。

<template>
<input type="text" v-model="name">
<input type="text" v-model="surname">
<button @click="addOrUpdateCustomer"></button>
</template>
<script>
import Vue from "vue";
export default {
data(){
return{
name:"",
surname:"",
customers:[]      
}
},
methods:{
addOrUpdateCustomer() {
const customerAtIndex = this.customers.findIndex(c => c.name === this.name);
//existing customer
if(customerAtIndex > -1) {
// You can update anything here 
let existingCustomer = this.customers[customerAtIndex];
existingCustomer.surname = this.surname;
this.customers[customerAtIndex] = existingCustomer;
}
else {
//new customer 
this.customers.push({name: this.name, surname: this.surname});
}

}
}
}
</script>

我认为这里有一个误解。customers是一个空对象数组,它可以(也可以不)包含客户的信息。但是您不一定需要创建空对象作为占位符。JS中的Array有不同的方法可以用来实现你想要的。

在你的例子中,它可以是这样的:

addCustomer(){
let findIndex = this.customers.findIndex((customer) => customer.name === this.name );
let isInArray = findIndex !== -1;
if (!isInArray){
this.customers.push("name", "Nacho")
}
}

如果客户不在数组中,则假定您想要添加它。如果它在数组中…那就看你的逻辑了。但是你可以使用slice数组方法来删除它。

顺便说一句,没有必要使用Vue。方法,因为push方法在这种情况下是相同的(Vue负责新插入的值,所以它是响应的)。

作为上面的一个用户,我也相信你有一个误解。

数组只是一个客户列表,对象只包含客户的属性,如果列表中没有客户,则不需要添加对象。

一个购物车需要5个水果,如果购物车是空的,我不需要在购物车上添加空字符串。

如果数组需要5个数字,但如果数组为空,则不需要在数组

中添加0

s作为占位符。你想做这样的事情

const cart = ["", "", "", "", ""] 
const array = [0, 0, 0, 0, 0] 

根本没有理由这样做。

如果要限制数组的大小,可以在数组长度达到限制时停止函数。

例如

// stop the function if the array size is at 3
// means the size limit is 3
if (array.length === 3) return
const addCustomer = () => {
if (array.length === 3) return
array.push(value) // replace value with customer or whatever you want to add
}

一个实现的例子(组合API)

选项API

示例

最新更新