如果要洗掉資料,我找到帶有 findIndex 的元素并將其作為空值丟棄在 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>
uj5u.com熱心網友回復:
從你的問題中理解,如果你想將客戶添加到串列中,如果不是按名稱在客戶中,如果存在,則從串列中更新現有客戶。
那么你的代碼應該是這樣的。
<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>
uj5u.com熱心網友回復:
我認為這里有一個誤解。customers是一個空物件陣列,它可以(或不)包含您的客戶的資訊。但是您不一定需要創建空物件作為占位符。Array在 JS 中有不同的方法可以用來實作你想要的。像push方法一樣在陣列的末尾添加一個元素或slice來洗掉它。
在您的示例中,它可能類似于:
addCustomer(){
let findIndex = this.customers.findIndex((customer) => customer.name === this.name );
let isInArray = findIndex !== -1;
if (!isInArray){
this.customers.push("name", "Nacho")
}
}
如果客戶不在陣列中,則假設您要添加它。如果它在陣列中……那么這取決于您的邏輯。但是您可以使用slice陣列方法將其洗掉。
順便說一句,不需要使用 Vue.set 方法,因為 push 方法在這種情況下是相同的(Vue 負責處理新插入的值,因此它是反應式的)。
uj5u.com熱心網友回復:
正如上面的用戶所說,我也相信你有一個誤解。
陣列只是客戶串列,物件只是包含客戶的屬性,如果串列中沒有客戶,則無需添加物件。
一輛推車需要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
}
您的實施示例(Composition API)
選項 API 中的示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/533663.html
上一篇:頁腳不粘在底部引導程式5.2.2
