Vuejs技术栈--状态管理

Vuejs技术栈--状态管理vuex

安装

npm install --save vuex

状态文件:store/state.js

export default {
  latitude: 40.10038, // 纬度
  longitude: 116.36867, // 经度
  address: {}, // 地址信息对象
  categorys: [], // 分类数组
  ...
}

记录信号识别常量:store/mutation-types.js

export const RECEIVE_ADDRESS = 'receive_address' // 接收地址信息
export const RECEIVE_CATEGORYS = 'receive_categorys' // 接收分类数组
export const RECEIVE_SHOPS = 'receive_shops' // 接收商家数组

对state的数据处理:store/mutations.js

import {
RECEIVE_ADDRESS,
RECEIVE_CATEGORYS,
RECEIVE_SHOPS
} from './mutation-types'
export default {
[RECEIVE_ADDRESS](state, {address}) {
state.address = address
},
[RECEIVE_CATEGORYS](state, {categorys}) {
state.categorys = categorys
},
[RECEIVE_SHOPS](state, {shops}) {
state.shops = shops
},
}
View Code

逻辑处理:store/actions.js

import {reqAddress, reqCategorys, reqShops} from '../api'
import {RECEIVE_ADDRESS, RECEIVE_CATEGORYS, RECEIVE_SHOPS} from './mutation-types'
export default {
// 异步获取地址
async getAddress({commit, state}) {
const geohash = state.latitude + ',' + state.longitude
const result = await reqAddress(geohash)
commit(RECEIVE_ADDRESS, {address: result.data})
},
// 异步获取分类列表
async getCategorys({commit}) {
const result = await reqCategorys()
commit(RECEIVE_CATEGORYS, {categorys: result.data})
},
// 异步获取商家列表
async getShops({commit, state}) {
const {latitude, longitude} = state
const result = await reqShops({latitude, longitude})
commit(RECEIVE_SHOPS, {shops: result.data})
}
}
View Code
包含多个基于state的getter计算属性的对象:store/getters.js
/*
包含多个基于state的getter计算属性的对象
 */
export default {

  totalCount (state) {
    return state.cartFoods.reduce((preTotal, food) => preTotal + food.count , 0)
  },

  totalPrice (state) {
    return state.cartFoods.reduce((preTotal, food) => preTotal + food.count*food.price , 0)
  },

  positiveSize (state) {
    return state.ratings.reduce((preTotal, rating) => preTotal + (rating.rateType===0?1:0) , 0)
  }
}

把store暴露出来:store/index.js

/*
vuex最核心的管理对象store
 */
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
View Code

main.js注册store

import store from './store'
new Vue({
  store
})

https://vuex.vuejs.org/guide/state.html

mapState、mapGetters、mapActions、mapMutations

computed: {
...mapState(['cartFoods', 'info']),
...mapGetters(['totalCount', 'totalPrice'])
}

this.$store.dispatch('getAddress')

import {mapAction} from 'vuex'

...mapAction(['getAddress'])

猜你喜欢

转载自www.cnblogs.com/xiaohuai/p/9170300.html