Vuex 使用心得

Fork Me On Github

为什么用

实现多页面同步共享数据,全局状态管理,也可以当作内存缓存来用

怎么用

简单使用

通过 state 存储数据

通过 computed 实现方法获取 state 中的值或定义getters 获取

定义 mutations 更新 state 数据, 通过 store.commit 触发 mutation

定义 actions 封装 store.commit 触发

多模块

modules 每一个模块实现 state getters mutations actions

如果模块内方法重名,则需要 在模块内加上 namespaced: true, 使用时需要加上模块名才能访问指定模块 state.模块名.属性名;反之直接访问即可

注意

state 并不能默认请求内容,要先 store.commit 设置内容,也可以定义action 异步获取并设置

ts
            
getCategories(context: {commit: Commit; state: State}) {
    return new Promise((resolve, reject) => {
        if (context.state.categories && context.state.categories.length > 0) {
            resolve(context.state.categories);
            return;
        }
        getCategories().then(res => {
            context.commit(SET_CATEGORIES, res.data);
            resolve(res.data);
        }).catch(reject);
    });
},
123456789101112

完整例子

ts
                                                                  
import Vue from 'vue'
import Vuex, { Commit, Dispatch } from 'vuex'
import {
    getCategories,
} from '@/api'

Vue.use(Vuex)

export const SET_CATEGORIES = 'SET_CATEGORIES';

export interface State {
    categories: ICategory[],
};

export interface ICategory {
    id: number,
    name: string,
}

interface IActionContext {
    commit: Commit;
    state: State;
}

// initial state
const initState: State = {
    categories: [],
};

const getters = {};

const mutations = {
    [SET_CATEGORIES](state: State, categories: ICategory[]) {
        state.categories = categories;
    },
};

// actions
const actions = {
    getCategories(context: IActionContext) {
        return new Promise((resolve, reject) => {
            if (context.state.categories && context.state.categories.length > 0) {
                resolve(context.state.categories);
                return;
            }
            getCategories().then((res: ICategory[]) => {
                context.commit(SET_CATEGORIES, res.data);
                resolve(res.data);
            }).catch(reject);
        });
    },
};

const store = new Vuex.Store({
    state: initState,
    getters,
    actions,
    mutations,
});

/// 方便typscript 类型推导
export const dispatchCategories = (): Promise<ICategory[]> => store.dispatch('getCategories');

export default store;

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
点击查看全文
标签: vue
0 405 0
升级vue3记录
2021年08月
最近有空折腾一下vue3,把以前的vue项目从vue2升级到vue3
滚动加载的页面默认无法后退保存之前的滚动位置,这么解决
玩转vue和小程序
vue 实现左滑删除,右滑点赞,一个滑动其他的复原!