以下是一个简单的 uniapp 购物车代码示例,可以根据实际需求进行修改和扩展。

  1. 在 vue 文件中添加购物车按钮:
<template>
  <div>
    <button @click='addToCart'>加入购物车</button>
  </div>
</template>

<script>
export default {
  methods: {
    addToCart() {
      // 向购物车添加商品
      this.$store.commit('addToCart', this.product);
    }
  }
}
</script>
  1. 在 store.js 中添加购物车状态和 mutations:
const store = new Vuex.Store({
  state: {
    cart: [] // 购物车状态
  },
  mutations: {
    addToCart(state, product) {
      // 添加商品到购物车
      const item = state.cart.find(item => item.id === product.id);
      if (item) {
        item.quantity++;
      } else {
        state.cart.push({
          id: product.id,
          name: product.name,
          price: product.price,
          quantity: 1
        });
      }
    },
    removeFromCart(state, product) {
      // 从购物车中删除商品
      const index = state.cart.findIndex(item => item.id === product.id);
      if (index !== -1) {
        state.cart.splice(index, 1);
      }
    }
  }
});
  1. 在购物车页面中显示购物车内容:
<template>
  <div>
    <div v-for='item in cart' :key='item.id'>
      <p>{{ item.name }}</p>
      <p>{{ item.price }}</p>
      <p>{{ item.quantity }}</p>
      <button @click='removeFromCart(item)'>删除</button>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    cart() {
      return this.$store.state.cart;
    }
  },
  methods: {
    removeFromCart(product) {
      // 从购物车中删除商品
      this.$store.commit('removeFromCart', product);
    }
  }
}
</script>
uniapp 购物车代码示例:实现商品添加和删除功能

原文地址: https://www.cveoy.top/t/topic/nx9C 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录