vue-vuex

13 篇文章 0 订阅

一、vuex基本概念
vuex 是一个专为 vue.js 应用程序开发的状态管理模式。可以理解为我们项目中需要共享的一些数据进行集中管理的容器。把这些数据称为属性状态。比如一个用户的用户名,性别,权限级别等等。
一般小项目里只用简单的状态管理,中型大型项目里用的多。

二、引入挂载

import simpleStore from './store/simpleStore'

Vue.prototype.$simpleStore = simpleStore

三、核心
1、state

//所有需要共享的数据都存放在 state 中
new Vuex.Store({
    state: {
        token: '',
        todos: [
            { id: 1, text: '...', done: true },
            { id: 2, text: '...', done: false }
        ]
    },
})
// 直接调用
this.$store.state.token

2、getter

//可以对state进行过滤与加工,可以认为是 store 的计算属性
new Vuex.Store({
    getters: {
        // state 作为其第一个参数
        doneTodos: state => {
            return state.todos.filter(todo => todo.done)
        },
        // getters 可作为第二个参数
        doneTodosCount: (state, getters) => {
            return getters.doneTodos.length
        },
        // 让 getter 返回一个函数,来实现给 getter 传参,对 store 里的数组进行查询时非常有用
        getTodoById: state => id => {
            return state.todos.find(todo => todo.id === id)
        }
        // 使用:this.$store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
    },
})
// 直接调用
this.$store.getters.doneTodos

3、mutations

//在 Vuex 中只能通过提交 mutation 来修改 store 中的状态,且是一个同步的过程
new Vuex.Store({
    mutations: {
        // state 作为第一个参数,接收第二个参数为传入的对象
        setToken (state, obj) {
            const st = state
            st.token = obj
        }
    },
})
// 直接调用
this.$store.commit('setToken', obj)

4、actions

//通过调用 mutation 方法异步的改变 state 状态
new Vuex.Store({
    actions: {
        // context 对象作为第一个参数,与 store 实例具有相同方法和属性,但不是 store 实例本身
        login (context) {
            context.commit('SET_TOKEN')
            console.log(context.state)
            console.log(context.getters)
        }
        // es2015 参数结构的方式,接收第二个对象作为参数传入
        login ({ commit, state, getters }, obj) {
            commit('SET_TOKEN')
        }
        // 异步操作,例:
        login ({ commit }, params) {
            const { account, pwd } = params
            // 定义一个promise
            return new Promise((resolve, reject) => {
                // 异步操作
                Vue.prototype.$apis.login({ account: account, pwd: pwd }).then(response => {
                    if (response.code === '000') {
                        const { data } = response
                        // 调用mutation
                        commit('SET_TOKEN', data.token)
                        setToken(data.token)
                        // 可以在成功后传出数据
                        resolve(data.loginStats)
                    } else {
                        reject(response.message)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        }
        // 组合 action,利用async await和dispatch来实现多action的嵌套调用
        async actionB ({ dispatch, commit }) {
            await dispatch('actionA') // 等待 actionA 完成
            commit('gotOtherData', await getOtherData())
        }
    },
})
// 直接调用
this.$store.dispatch('login', obj)

6、modules

//将 store 分割成模块,每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
// 定义一个 user.js 模块
const user = {
    namespaced: false,
    state: {
        userInfo: {}
    },
    getters: {
        // rootState是根节点状态
        getUser (state, getters, rootState) {}
    },
    mutations: {
        setUser (state) {}
    },
    actions: {
        // rootState是根节点状态
        getUserInfo ({ state, commit, rootState }) {}
    }
}

export default user

// 在store.js中导入
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user' // 导入模块user

Vue.use(Vuex)

export default new Vuex.Store({
    state: {},
    getters: {},
    mutations: {},
    actions: {},
    modules: {
        user
    }
})
//默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的,只有state注册在自己的模块内,调用需要加上模块名。
// state
computed: {
    ...mapState({
        userInfo: state => state.user.userInfo
    })
    ...mapGetters({
        getUser: 'getUser'
    })
}
// getters
this.$store.getters.getUser
// mutations
this.$store.commit('setUser', obj)
// actions
this.$store.dispatch('getUserInfo', obj)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值