Vuex仿饿了么购物车功能
生活随笔
收集整理的這篇文章主要介紹了
Vuex仿饿了么购物车功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
餓了么購物車功能
今天通過Vuex完成了基本的購物車功能,對Vuex的store和mutation有了進一步認識。
實現購物車所需要的數據
store作為可以全局訪問的數據倉庫,滿足了我們在任意一個組件使用數據的需求。所以,我預先在store里聲明三個變量:f_count數組類型,cart_list數組類型,cart_item 整數類型,以便在全局調用。
代碼如下:
添加和刪除商品方法
main.js中
mutations:{//操作共享數據,只能用mutations提供的方法//如果組件要使用mutations定義的方法,只能使用 this.$store.commit('函數名');increment(state,i){ //當前商品fid,在cart_list中的索引var tmp_index = state.cart_list.indexOf(i.fid);if(!state.cart_list.includes(i.fid)){//如果商品未存在于cart_list,//則將商品對象加入cart_list//并且在f_count對應索引位置添加值state.f_count.push(1);state.cart_list.push(i.fid);}else{//如果商品已存在,則把f_count對應索引位置的值+1state.f_count[tmp_index]++;} },subtract(state,i){var tmp_index = state.cart_list.indexOf(i.fid);state.f_count[tmp_index]--;if(state.f_count[tmp_index]==0){//刪除商品對象在f_count和cart_list中對應的值state.f_count.splice(tmp_index,1);state.cart_list.splice(tmp_index,1);}},//計算購物車內商品總件數 cart_itemitem_sum(state){if(state.f_count.length==1){state.cart_item = state.f_count[0];}else{state.cart_item =0;for(var n in state.f_count){state.cart_item+=state.f_count[n]}}}},}操作購物車組件 counter.vue
//模板部分 <template><div class='active_btn'><transition name="fade"><div class='del_cart' v-show='item.count'><div @click='delCart(item)'>-</div></div></transition><span v-show="item.count">{{item.count}}</span><div class='add_cart'><div @click="addCart(item)">+</div></div></div> </template> import Vue from 'vue';export default {data(){return{}},props:['item'],//從父組件接收傳值methods:{addCart(item){this.$store.commit('increment',item); //改變狀態里的f_count,購物車內商品數量//記錄單個商品的數量和值if(!item.count){Vue.set(item,'count',1);}else{item.count++;}this.i_count=item.count;this.$store.commit("item_sum"); //計算購物車內商品總件數},delCart(item){this.$store.commit('subtract',item);item.count--;this.$store.commit("item_sum");},}}點單頁面 shopDetails.vue
由于counter.vue是作為子組件嵌套在shopDetails.vue中的,所以必要的傳值不可少
計算屬性獲取store中cart_item的值
computed:{cart_item(){return this.$store.state.cart_item;}},最后實現效果,當添加商品時,單個商品數量,和商品總數量會相應改變。
明天計劃:
1.購物車展開詳情:商品單價,商品數量,總計,折扣
2.商品詳情頁:商品大圖,商品描述,價格,留言等
總結
以上是生活随笔為你收集整理的Vuex仿饿了么购物车功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1、ipywidgets
- 下一篇: vue3 项目搭建以及使用