倉庫位址:https://github.com/dubuxunqi/vuexShoppingCar
先看下效果圖
看下目錄結構:
安裝vue腳手架,還有布局就不在說了,主要講vuex的用法
1.安裝vuex依賴 npm install vuex --save
2.先是在src路徑下建立一個vuex檔案夾store,裡面建立一個入口檔案index.js。引入VUE、VUEX兩大神器,然後在main.js裡面引入一下,目的是讓vuex在整個項目中都能通路到
index.js裡面的代碼:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import mutations from './mutations'
import actions from './actions'
import state from './states'
import getters from './getters'
export default new Vuex.Store({
mutations,
actions,
state,
getters
})
main.js的代碼:
import store from './store/'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
3.在store檔案夾中建立states.js,state是儲存資料用的
export default{
arr:[]
}
4.在store檔案夾中建立mutations.js,即mutation對象,它是更改store狀态的唯一方法。點選清單頁面的加入購物車,修改state對象裡面的資料,并且修改的資料要送出到背景,但是mutation隻能進行同步操作,是以得用action對象(後面介紹)
import state from './states'
export default{
addGoods(state,info){ //加入購物車的方法 參數state是state對象,info是addGoods調用時的參數,即傳入加入購物車物品的對象
let isOwn = state.arr.some(function(item){
if(item.id == info.id){
item.num++;
return true;
}else{
return false;
}
});
if(!isOwn){
state.arr.push({id:info.id,name:info.name,price:info.price,num:1});
}
},
addNum(state,index){ //購物車中增加物品數量
state.arr[index].num++;
},
reduceNum(state,index){ //購物車中減少物品數量
if(state.arr[index].num == 0){
state.arr.splice(index,1);
}else{
state.arr[index].num--;
}
},
deleteGoods(state,index){ //購物車中删除物品
state.arr.splice(index,1);
}
}
5.在store檔案夾中建立actions.js,即action對象,Action 送出的是 mutation,而不是直接變更狀态。
Action 可以包含任意異步操作。(下面的例子不涉及異步操作,如果想要測試,自己加上setimeout測試下)
export default{
addGoods({commit},params){ //params對應mutation對象中參數info
commit('addGoods',params);
},
addNum({commit},params){
commit('addNum',params);
},
reduceNum({commit},params){
commit('reduceNum',params);
},
deleteGoods({commit},params){
commit('deleteGoods',params);
}
}
6.在store檔案夾中建立getters.js,即getter對象,getter對象可以處理state的資料,或是過濾
import state from './states'
export default{
totalMoney(state){
let money = 0; // 計算總價
for(let i =0;i<state.arr.length;i++){
money += parseInt(state.arr[i].price.substring(1))*state.arr[i].num;
}
return money;
}
}
7.list.vue裡面的代碼
js代碼
import {mapActions} from 'vuex' //引入action對象
export default{
name:"List",
data(){
return {
arr:[
{id:22,name:"小炒肉",price:"¥25.00"},
{id:13,name:"皮蛋瘦肉粥",price:"¥13.00"},
{id:36,name:"涼皮",price:"¥15.00"},
{id:19,name:"肉夾馍",price:"¥10.00"},
{id:28,name:"幹鍋鴨頭",price:"¥205.00"},
]
}
},
methods:{
...mapActions(['addGoods']) //使用action對象中addGoods方法
}
}
8.car.vue代碼
js代碼
import {mapState,mapActions,mapGetters} from 'vuex' //引入state,action,getter對象
export default{
name:"Car",
data(){
return {
}
},
methods:{
...mapActions(['addNum','reduceNum','deleteGoods'])
},
computed:{
...mapGetters(['totalMoney']),//在計算屬性裡面使用getter和state對象
...mapState(['arr'])
}
}
如果有什麼問題,盡管拍磚,虛心接受,有什麼問題也可以給我留言