(十六)硅谷外卖-使用 vuex 管理状态

Posted mxsf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(十六)硅谷外卖-使用 vuex 管理状态相关的知识,希望对你有一定的参考价值。

一、下载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
)

 

以上是关于(十六)硅谷外卖-使用 vuex 管理状态的主要内容,如果未能解决你的问题,请参考以下文章

(十四)硅谷外卖-后台应用(上)

vuex是什么,以及用vuex的好处,和单界面状态管理

(十三)硅谷外卖前端部分-Login 组件(静态)

vue状态管理(vuex)

VSCode自定义代码片段13——Vue的状态大管家

VSCode自定义代码片段13——Vue的状态大管家