前端Vue日常工作中--对象数组的处理

前端Vue日常工作中–对象数组的处理

1.基本说明

首先,对象数组是指一个数组,其中每个元素都是一个对象而不是基本数据类型。数组可以包含不同类型的元素,包括对象。对象数组允许你在一个数组中存储多个对象实例,并通过数组索引访问它们。

数组的大部分方法也可以用于对象数组,简单介绍可以看下面链接中的数组总结:

前端Vue日常工作中–Js数组常用方法

日常工作中,前端从后端拿到最多的就是json对象数组,同时要将它们结合对应的框架进行渲染和处理,这里简单总结一下,在Vue.js中处理对象数组经常使用的方法:

1.1 循环

  1. 使用 v-for 指令:
    v-for 是Vue.js提供的指令,用于在模板中迭代数组或对象。

    <template>
      <div>
        <ul>
          <li v-for="item in items" :key="item.id">{{ item.name }}</li>
        </ul>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          items: [
            { id: 1, name: 'Item 1' },
            { id: 2, name: 'Item 2' },
            { id: 3, name: 'Item 3' }
          ]
        };
      }
    };
    </script>
    
  2. 使用 forEach 方法:
    forEach 是数组的方法,用于遍历数组中的每个元素。

    <script>
    export default {
      data() {
        return {
          items: [
            { id: 1, name: 'Item 1' },
            { id: 2, name: 'Item 2' },
            { id: 3, name: 'Item 3' }
          ]
        };
      },
      mounted() {
        this.items.forEach(item => {
          console.log(item.name);
        });
      }
    };
    </script>
    
  3. 使用 for in 循环:
    for in 循环用于遍历对象的可枚举属性。

    <script>
    export default {
      data() {
        return {
          items: {
            1: { id: 1, name: 'Item 1' },
            2: { id: 2, name: 'Item 2' },
            3: { id: 3, name: 'Item 3' }
          }
        };
      },
      mounted() {
        for (let key in this.items) {
          console.log(this.items[key].name);
        }
      }
    };
    </script>
    
  4. 使用 for of 循环:
    for of 循环用于遍历可迭代对象(如数组、字符串、Map等)的值。

    <script>
    export default {
      data() {
        return {
          items: ['Item 1', 'Item 2', 'Item 3']
        };
      },
      mounted() {
        for (let item of this.items) {
          console.log(item);
        }
      }
    };
    </script>
    

1.2 过滤

使用Array.filter方法可以根据特定条件过滤数组。

computed: {
  filteredItems() {
    return this.items.filter(item => item.property === 'desiredValue');
  }
}

简单例子:

<template>
  <ul>
    <li v-for="(item, index) in filteredItems" :key="index">
      {{ item.name }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ]
    };
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => item.id > 1);
    }
  }
};
</script>

1.3 映射

使用Array.map方法可以根据数组的每个元素创建一个新数组。

computed: {
  mappedItems() {
    return this.items.map(item => item.property + ' - Modified');
  }
}

简单例子:

<template>
  <ul>
    <li v-for="(modifiedItem, index) in mappedItems" :key="index">
      {{ modifiedItem }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ]
    };
  },
  computed: {
    mappedItems() {
      return this.items.map(item => item.name + ' - Modified');
    }
  }
};
</script>

1.4 查找

使用Array.find方法可以查找数组中符合条件的第一个元素。

methods: {
  findItem() {
    const selectedItem = this.items.find(item => item.property === 'desiredValue');
    console.log(selectedItem);
  }
}

简单例子:

<template>
  <div>
    <p>Item found: {{ foundItem ? foundItem.name : 'Not found' }}</p>
    <button @click="findItem">Find Item</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ],
      foundItem: null
    };
  },
  methods: {
    findItem() {
      this.foundItem = this.items.find(item => item.id === 2);
    }
  }
};
</script>

1.5 排序

使用Array.sort方法可以对数组进行排序。

methods: {
  sortItems() {
    this.items.sort((a, b) => a.property.localeCompare(b.property));
  }
}

简单例子:

<template>
  <ul>
    <li v-for="(item, index) in sortedItems" :key="index">
      {{ item.name }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 3, name: 'Item 3' },
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' }
      ]
    };
  },
  computed: {
    sortedItems() {
      return this.items.slice().sort((a, b) => a.id - b.id);
    }
  }
};
</script>

1.6 增删改查

使用Array.pushArray.popArray.shiftArray.unshift等方法可以对数组进行增删改操作。

methods: {
  addItem() {
    this.items.push({ property: 'newItem' });
  },
  removeItem(index) {
    this.items.splice(index, 1);
  },
  updateItem(index) {
    this.$set(this.items, index, { property: 'updatedValue' });
  }
}

简单例子:

<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item.name }}
        <button @click="removeItem(index)">Remove</button>
      </li>
    </ul>
    <button @click="addItem">Add Item</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ]
    };
  },
  methods: {
    addItem() {
      const newItem = { id: this.items.length + 1, name: 'New Item' };
      this.items.push(newItem);
    },
    removeItem(index) {
      this.items.splice(index, 1);
    }
  }
};
</script>

2.父子组件中(举例说明)

2.1 待办任务列表

父组件

<template>
  <div>
    <h1>待办事项列表</h1>
    <ChildComponent :tasks="tasks" @addTask="addTask" />
    <p>父组件中的任务列表:</p>
    <ul>
      <li v-for="task in tasks" :key="task.id">{{ task.name }}</li>
    </ul>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  data() {
    return {
      tasks: [
        { id: 1, name: '任务 1', completed: false },
        { id: 2, name: '任务 2', completed: true },
        { id: 3, name: '任务 3', completed: false },
      ],
    };
  },
  methods: {
    addTask(newTask) {
      this.tasks.push(newTask);
    },
  },
  components: {
    ChildComponent,
  },
};
</script>

子组件

<template>
  <div>
    <h2>添加任务</h2>
    <input v-model="newTask.name" placeholder="任务名称" />
    <el-checkbox v-model="newTask.completed">已完成</el-checkbox>
    <el-button type="primary" @click="addTaskToParent">添加任务</el-button>
  </div>
</template>

<script>
export default {
  props: {
    tasks: Array,
  },
  data() {
    return {
      newTask: { name: '', completed: false },
    };
  },
  methods: {
    addTaskToParent() {
      if (this.newTask.name.trim() !== '') {
        const newTask = {
          id: Date.now(),
          name: this.newTask.name,
          completed: this.newTask.completed,
        };
        this.$emit('addTask', newTask);
        this.newTask = { name: '', completed: false }; // 清空输入框
      } else {
        alert('请输入任务名称。');
      }
    },
  },
};
</script>

使用简单的文本输入框和一个复选框来输入任务名称和完成状态,以及 Element UI 的 el-checkbox 组件。

父组件显示一个任务列表,并将任务数组传递给子组件。子组件允许用户添加新任务,包括任务名称和完成状态。当在子组件中添加新任务时,它会触发一个带有新任务数据的 addTask 事件,父组件捕获该事件并将新任务添加到其任务数组中。

2.2 购物车

父组件

<template>
  <div>
    <h1>购物车</h1>
    <ChildComponent :cartItems="cartItems" @addToCart="addToCart" />
    <p>购物车中的商品:</p>
    <el-table :data="cartItems" style="width: 100%">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
    </el-table>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  data() {
    return {
      cartItems: [
        { id: 1, name: '商品1', price: 20 },
        { id: 2, name: '商品2', price: 30 },
        { id: 3, name: '商品3', price: 25 },
      ],
    };
  },
  methods: {
    addToCart(newItem) {
      this.cartItems.push(newItem);
    },
  },
  components: {
    ChildComponent,
  },
};
</script>

子组件

<template>
  <div>
    <h2>添加商品到购物车</h2>
    <el-form :model="newItem" label-position="top" style="max-width: 300px;">
      <el-form-item label="商品名称">
        <el-input v-model="newItem.name"></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model.number="newItem.price" type="number"></el-input>
      </el-form-item>
      <el-button type="primary" @click="addItemToCart">添加到购物车</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    cartItems: Array,
  },
  data() {
    return {
      newItem: { name: '', price: 0 },
    };
  },
  methods: {
    addItemToCart() {
      if (this.newItem.name.trim() !== '' && this.newItem.price > 0) {
        const newItem = {
          id: Date.now(),
          name: this.newItem.name,
          price: this.newItem.price,
        };
        this.$emit('addToCart', newItem);
        this.newItem = { name: '', price: 0 }; // 清空输入框
      } else {
        alert('请输入有效的商品名称和价格。');
      }
    },
  },
};
</script>

使用Element UI的el-tableel-form组件,以及Vue.js的数据绑定和事件触发。

父组件展示了购物车中的商品列表,而子组件包含一个表单,用于添加新商品到购物车。当在子组件中输入新的商品信息并点击"添加到购物车"按钮时,新的商品将通过事件传递到父组件并添加到购物车数组中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狐说狐有理

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值