vuex Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式新锈。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài)芦缰,并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化, 在項目中相當(dāng)于一個數(shù)據(jù)倉庫的意思高职。
新建一個store.js文件藐吮, 代碼如下:
import?Vue?from?'vue'
import?Vuex?from?'vuex'
Vue.use(Vuex)
const?store?=?new?Vuex.Store({
????state:{
????????cart:?JSON.parse(localStorage.getItem('cart'))?||?[]
????},
????mutations:{
????????addCart(state,?item){
????????????let?good?=?state.cart.find(v?=>v.name==item.name)
????????????if(good){
????????????????good.count?+=?1
????????????}
????????????else{
????????????????state.cart.push({...item,?count:?1})
????????????}
????????},
????????cart_add(state,?index){
????????????state.cart[index].count?+=1
????????},
????????cart_reduce(state,?index){
????????????if(state.cart[index].count?>?1){
????????????????state.cart[index].count?-=?1
????????????}
????????},
????},
?????//?相當(dāng)于vuex內(nèi)部的computed
?????getters:{
????????total_cart:state?=>?{
????????????let?sum?=?0
????????????state.cart.forEach(v?=>?{
????????????????sum?+=?v.count
????????????})
????????????return?sum
????????}
????}
})
//?監(jiān)視?vuex中state和mutations?的變化
store.subscribe((mutations,?state,)=>{
????localStorage.setItem('cart',?JSON.stringify(state.cart))
})
export?default?store
其中?state 作為數(shù)據(jù)倉庫, 存儲數(shù)據(jù)卤档,?mutations 里面存放的是對數(shù)據(jù)操作的方法蝙泼。 state?相當(dāng)于現(xiàn)實生活后勤部,?mutations相當(dāng)于申請單劝枣, 需要對倉庫里的東西干啥汤踏。
getters:就是相當(dāng)于vuex內(nèi)部的computed
store.subscribe 用作對state,?mutations l里面變化的監(jiān)視
調(diào)用mutations 中的方法:this.$store.commit(方法名, 參數(shù))
add:function(i){? ?this.$store.commit('cart_add',?i)????????},
調(diào)用state:
import?{mapState}?from?'vuex'
export?default?{
????computed:{
????????...mapState({
????????????carts:?state=>state.cart
????????}),
????????total(){
????????????return?this.carts.reduce((sum,?v)=>{
????????????????return?sum?+=?v.price?*?v.count
????????????},?0)
????????}
????},
????methods:{
????????add:function(i){
????????????this.$store.commit('cart_add',?i)
????????},
????????reduce_cart(i){
????????????this.$store.commit('cart_reduce',?i)
????????}
????}
}
引用getters:
import?{mapGetters}?from?'vuex'
export?default?{
????computed:{
???????...mapGetters({
???????????cartTotal:'total_cart'
???????})
???},
}