如何使用Vue.js从对象数组中选取特定对象的指定信息展示
完全可以,这正是Vue.js声明式渲染的核心能力之一,只需要结合v-for指令循环遍历商品数组,再通过双大括号语法或者v-bind绑定对应字段即可实现动态渲染,同时可以直接搭配加入购物车的业务逻辑使用。
完整实现示例
模板代码(结合你原有的Bootstrap卡片结构改造)
<template> <div class="container mt-4"> <div class="row"> <!-- 循环遍历商品数组,key绑定唯一商品id --> <div v-for="product in shop" :key="product.id" class="col-md-6 col-lg-4 d-flex justify-content-center mb-4" > <div class="card" style="width: 18rem;"> <!-- 动态绑定商品图片,建议你给商品对象新增imgName字段存储对应图片文件名 --> <img :src="`./assets/images/${product.imgName}`" :alt="product.name" class="card-img-top rounded" > <div class="card-body"> <!-- 渲染商品名称 --> <h5 class="card-title">{{ product.name }}</h5> <!-- 渲染商品价格,格式化为标准金额样式 --> <p class="card-text">¥{{ product.price.toFixed(2) }}</p> <!-- 绑定加入购物车点击事件,传入当前循环对应的商品对象 --> <button class="btn btn-danger" @click="addToCart(product)"> <i class="bi bi-cart-plus"></i> 加入购物车 </button> </div> </div> </div> </div> <!-- 可选扩展:购物车预览区域 --> <div class="mt-5" v-if="cart.length"> <h3>购物车</h3> <ul class="list-group"> <li v-for="item in cart" :key="item.id" class="list-group-item d-flex justify-content-between align-items-center"> {{ item.name }} × {{ item.quantity }} <span>¥{{ (item.price * item.quantity).toFixed(2) }}</span> </li> <li class="list-group-item fw-bold"> 总价:¥{{ totalPrice.toFixed(2) }} </li> </ul> </div> </div> </template>
逻辑代码(Vue3 选项API写法,兼容性更强)
<script> export default { data() { return { // 你的商品数组,新增imgName字段对应每张商品图的文件名即可,不需要保留中文名称可删除我新增的译名 shop: [ { id : 1, name: "Spotify Plaque", price: 150, quantity: 0, imgName: "spotifyplaque.jpg" }, { id : 2, name: "Keychain", price: 35, quantity: 0, imgName: "keychain.jpg" }, { id : 3, name: "Cards", price: 30, quantity: 0, imgName: "cards.jpg" }, { id : 4, name: "Spotify Keychain", price: 35, quantity: 0, imgName: "spotifykeychain.jpg" }, { id : 5, name: "Mugs", price: 70, quantity: 0, imgName: "mugs.jpg" }, { id : 6, name: "Glass Cups", price: 70, quantity: 0, imgName: "glasscups.jpg" }, { id : 7, name: "Round Christmas Baubles", price: 45, quantity: 0, imgName: "roundbaubles.jpg" }, { id : 8, name: "Flat Christmas Baubles", price: 30, quantity: 0, imgName: "flatbaubles.jpg" } ], // 购物车存储数组 cart: [] } }, computed: { // 自动计算购物车总价 totalPrice() { return this.cart.reduce((sum, item) => sum + item.price * item.quantity, 0) } }, methods: { addToCart(product) { // 判断购物车是否已有当前商品 const existItem = this.cart.find(item => item.id === product.id) if (existItem) { // 已有对应商品则数量+1 existItem.quantity++ } else { // 无对应商品则新增到购物车 this.cart.push({ ...product, quantity: 1 }) } // 如果需要同步修改原商品数组的quantity字段,可新增下面一行代码 // product.quantity++ } } } </script>
核心逻辑说明
- 不需要手动编写8个商品卡片,通过
v-for="product in shop"遍历商品数组即可自动生成所有卡片 - 任意位置通过
{{ product.字段名 }}即可灵活读取当前商品的任意字段值渲染到页面 - 点击加入购物车时传入当前循环对应的商品对象,即可精准操作对应商品的购物车逻辑
- 如果不需要购物车预览功能,直接删除对应代码块即可,不影响基础渲染和加购功能
内容的提问来源于stack exchange,提问作者durellvicjardim
相关产品推荐
相关产品推荐

