使用 Vue 3 和 TypeScript 的 Vite 商城购物车实现示例

// ProductList.vue
<template>
  <div>
    <h2>商品列表</h2>
    <ul>
      <li v-for="product in products" :key="product.id">
        {{ product.name }}
        <button @click="addToCart(product)">加入购物车</button>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { useStore } from '../store';

export default defineComponent({
  setup() {
    const store = useStore();
    const products = [
      { id: 1, name: '商品1', price: 100 },
      { id: 2, name: '商品2', price: 200 },
      // 其他商品
    ];

    const addToCart = (product: { id: number; name: string; price: number }) => {
      store.commit('addToCart', product);
    };

    return {
      products,
      addToCart,
    };
  },
});
</script>

// ShoppingCart.vue
<template>
  <div>
    <h2>购物车</h2>
    <ul>
      <li v-for="(item, index) in cartItems" :key="index">
        {{ item.name }} - ¥{{ item.price }}
        <button @click="removeFromCart(index)">移出购物车</button>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { useStore } from '../store';

export default defineComponent({
  setup() {
    const store = useStore();
    const cartItems = store.state.cart;

    const removeFromCart = (index: number) => {
      store.commit('removeFromCart', index);
    };

    return {
      cartItems,
      removeFromCart,
    };
  },
});
</script>

// store/index.ts
import { createStore, Store } from 'vuex';

interface Product {
  id: number;
  name: string;
  price: number;
}

interface State {
  cart: Product[];
}

const store = createStore<State>({
  state: {
    cart: [],
  },
  mutations: {
    addToCart(state, product: Product) {
      state.cart.push(product);
    },
    removeFromCart(state, index: number) {
      state.cart.splice(index, 1);
    },
  },
});

export function useStore(): Store<State> {
  return store as Store<State>;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值