使用 vuex 对首页进行状态管理

目录结构

在 main.js 中注入 store

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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,
})

state.js

1
2
3
4
5
6
7
export default {
latitude: 40.10038, // 维度
longitude: 116.36867, // 经度
address: {}, // 地址相关信息对象
categories: [], // 食品分类数组
shops: [] // 商家数组
}

mutation_types.js

1
2
3
export const RECEIVE_ADDRESS = 'receive_address' // 接受地址
export const RECEIVE_CATEGORIES = 'receive_categories' // 接受食品数组
export const RECEIVE_SHOPS = 'receive_shops' // 接受商家数组

mutations.js

1
2
3
4
5
6
7
8
9
10
11
export default {
[RECEIVE_ADDRESS](state, {address}){
state.address = address
},
[RECEIVE_CATEGORIES](state, {categories}) {
state.categories = categories
},
[RECEIVE_SHOPS](state, {shops}) {
state.shops = shops
},
}

actions.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import {
RECEIVE_ADDRESS,
RECEIVE_CATEGORIES,
RECEIVE_SHOPS
} from './mutation-types'

import {
reqAddress,
reqFoodCategories,
reqShops
} from '../api'

export default {
// 异步获取地址
async getAddress({
commit,
state
}) {
// 发送异步ajax请求
const geohash = state.latitude + ',' + state.longitude
const result = await reqAddress(geohash)
// 根据结果提交一个mutation
// 获取成功 code===0
if (result.code === 0) {
const address = result.data
commit(RECEIVE_ADDRESS, {
address
})
}
},
// 异步获取食品分类数组
async getCategories({
commit,
}) {
// 发送异步ajax请求
const result = await reqFoodCategories()
// 根据结果提交一个mutation
if (result.code === 0) {
const categories = result.data
commit(RECEIVE_CATEGORIES, {
categories
})
}
},

// 异步获取商家数组
async getShops({
commit,state
}) {
// 发送异步ajax请求
const{longitude,latitude} = state
const result = await reqShops(longitude,latitude)
// 根据结果提交一个mutation
if (result.code === 0) {
const shops = result.data
commit(RECEIVE_SHOPS, {
shops
})
}
}
}

getters.js

无代码