【问题标题】:How to add data to a predefined object if there is no data?如果没有数据,如何向预定义对象添加数据?
【发布时间】:2022-11-15 06:35:16
【问题描述】:

如果要删除数据,我会使用 findIndex 找到元素并将其作为 null 值丢弃在 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>

【问题讨论】:

  • 目前尚不清楚您要达到什么目的。
  • @YardenBuzaglo 很清楚。查看客户数组。如果它已满,则不会向其添加数据,如果下一个索引为空,则会向其添加数据。

标签: javascript vue.js vuejs2


【解决方案1】:

我认为这里有一个误解。 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 负责处理新插入的值,因此它是反应式的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多