一、下载 Vuex
npm install --save vuex
二、定义 state
store/state.js
/* 状态对象 */ export default { latitude: 32.10038, // 纬度 longitude: 107.36867, // 经度 address: {}, // 地址信息对象 categorys: [], // 分类数组 shops: [] // 商家数组 }
二、定义 mutation-types
store/mutation-types.js
/* 包含n个mutation的type名称常量 */ export const RECEIVE_ADDRESS = 'receive_address' // 接收地址信息 export const RECEIVE_CATEGORYS = 'receive_categorys' // 接收分类数组 export const RECEIVE_SHOPS = 'receive_shops' // 接收商家数组
三、定义 mutations
store/mutations.js
/* 直接更新state的多个方法的对象 */ import { RECEIVE_ADDRESS, RECEIVE_CATEGORYS, RECEIVE_SHOPS } from '@/store/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 } }
四、定义 actions
store/actions.js
/* 通过mutation间接更新state的多个方法的对象 */ import { reqAddress, reqShops, reqCategorys } from '@/api' import { RECEIVE_ADDRESS, RECEIVE_CATEGORYS, RECEIVE_SHOPS } from '@/store/mutation-types' export default { // 异步获取地址 async getAddress ({commit, state}) { const geohash = state.latitude + ',' + state.longitude const result = await reqAddress(geohash) if (result.code === 0) { const address = result.data commit(RECEIVE_ADDRESS, {address}) } }, // 异步获取分类列表 async getCategorys ({commit}) { const result = await reqCategorys() if (result.code === 0) { const categorys = result.data commit(RECEIVE_CATEGORYS, {categorys}) } }, // 异步获取商家列表 async getShops ({commit, state}) { const {latitude, longitude} = state const result = await reqShops({latitude, longitude}) if (result.code === 0) { const shops = result.data commit(RECEIVE_SHOPS, {shops}) } } }
五、定义 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 })
六、注册 store
main.js
import store from './store' new Vue ({ store })
七、异步调用
mounted () { this.$store.dispatch('getAddress') }
八、读状态
<script> import {mapState} from 'vuex' computed: { ...mapState(['address', 'categorys']) } </script>