在現(xiàn)代Web開發(fā)中,Vue.js作為一個(gè)漸進(jìn)式JavaScript框架,憑借其靈活性和易用性,被廣泛應(yīng)用于構(gòu)建用戶界面和單頁(yè)應(yīng)用。最近,Vue 3.0版本的發(fā)布,更是引入了一系列新特性和優(yōu)化,使開發(fā)變得更加簡(jiǎn)便和強(qiáng)大。今天,我們將通過(guò)一個(gè)簡(jiǎn)單的購(gòu)物車功能來(lái)展示如何在Vue 3中實(shí)現(xiàn)添加和移除商品的功能。 ``` src │ ├── components │ ├── ProductList.vue │ ├── ShoppingCart.vue │ ├── App.vue ├── main.js ```
## 代碼實(shí)現(xiàn)
接著,創(chuàng)建一個(gè)新的Vue 3項(xiàng)目: ```bash vue create vue-shopping-cart cd vue-shopping-cart ``` ### 安裝必要的依賴
### 設(shè)置 Vuex Store ```javascript // store.js import { createStore } from 'vuex';
const store = createStore({ state: { products: [ { id: 1, name: 'Product A', price: 100 }, { id: 2, name: 'Product B', price: 200 }, ], cart: [], }, mutations: { ADD_TO_CART(state, product) { const item = state.cart.find(i => i.id === product.id); if (item) { item.quantity++; } else { state.cart.push({ ...product, quantity: 1 }); } }, REMOVE_FROM_CART(state, product) { const itemIndex = state.cart.findIndex(i => i.id === product.id); if (itemIndex > -1) { state.cart.splice(itemIndex, 1); } }, }, getters: { cartTotal(state) { return state.cart.reduce((total, item) => total + item.price * item.quantity, 0); }, }, });
export default store; ``` ### 配置入口文件
### 創(chuàng)建ProductList組件 ```vue <template> <div class='product-list'> <h2>Product List</h2> <ul> <li v-for='product in products' :key='product.id'> {{ product.name }} - ${{ product.price }} <button @click='addToCart(product)'>Add to Cart</button> </li> </ul> </div> </template>
<script> import { mapState, mapMutations } from 'vuex';
export default { computed: { ...mapState(['products']), }, methods: { ...mapMutations(['ADD_TO_CART']), addToCart(product) { this.ADD_TO_CART(product); }, }, }; </script>
<style scoped> .product-list { margin-bottom: 20px; }
button { margin-left: 10px; } </style> ``` ### 創(chuàng)建ShoppingCart組件
### 配置主組件 ```vue <template> <div id='app'> <ProductList /> <ShoppingCart /> </div> </template>
<script> import ProductList from './components/ProductList.vue'; import ShoppingCart from './components/ShoppingCart.vue';
export default { components: { ProductList, ShoppingCart, }, }; </script>
<style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; text-align: center; color: #2c3e50; } </style> ``` ## 運(yùn)行項(xiàng)目
訪問(wèn) [http://localhost:8080](http://localhost:8080),你應(yīng)該可以看到一個(gè)簡(jiǎn)單的產(chǎn)品列表和購(gòu)物車。當(dāng)你點(diǎn)擊“Add to Cart”按鈕時(shí),商品將會(huì)被添加到購(gòu)物車;同時(shí),你可以通過(guò)點(diǎn)擊“Remove”按鈕將商品從購(gòu)物車中移除。 |
|