一、下载vuex
npm install --save vuex
二、定义state
store/state.js
export default { latitude: 40.10038, // 纬度 longitude: 116.36867, // 经度 address: {}, // 地址信息对象 categorys: [], // 分类数组 shops: [], }
三、定义mutation-types
store/mutation-types.js
export const RECEIVE_ADDRESS = ‘receive_address‘ // 接收地址信息 export const RECEIVE_CATEGORYS = ‘receive_categorys‘ // 接收分类数组 export const RECEIVE_SHOPS = ‘receive_shops‘ // 接收商家数组
四、定义mutations
store/mutations.js
import {RECEIVE_ADDRESS, RECEIVE_SHOPS, RECEIVE_CATEGORYS} from "./mutation-types" export default { [RECEIVE_ADDRESS](state, {address}) { state.address = address }, [RECEIVE_SHOPS](state, {categorys}) { state.categorys = categorys }, [RECEIVE_CATEGORYS](state, {shops}) { state.shops = shops } }
五、定义actions
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, {category: result.data}) }, // 异步获取商家列表 async getShops({commit, state}) { const {latitude, longitude} = state const result = await reqShops({latitude, longitude}) commit(RECEIVE_SHOPS, {shops: result.data}) } }
六、定义getters
store/getters.js
export default { }
七、定义store对象
store/index.js
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 })
原文地址:https://www.cnblogs.com/mxsf/p/10990457.html
时间: 2024-10-08 06:39:02