Vuex -- Store状态管理

1 篇文章 0 订阅

Vuex 是什么?

        Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

什么是“状态管理模式”?

从一个简单的 Vue 计数应用开始:

new Vue({
  // state
  data () {
    return {
      count: 0
    }
  },
  // view
  template: `
    <div>{{ count }}</div>
  `,
  // actions
  methods: {
    increment () {
      this.count++
    }
  }
})

这个状态自管理应用包含以下几个部分:

  • state,驱动应用的数据源;
  • view,以声明方式将 state 映射到视图;
  • actions,响应在 view 上的用户输入导致的状态变化。

以下是一个表示“单向数据流”理念的极简示意:

                                                                                                                                            vuex

什么情况下应该使用 Vuex?

        虽然 Vuex 可以帮助我们管理共享状态,但也附带了更多的概念和框架。这需要对短期和长期效益进行权衡。

        如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的 store 模式就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。

Vuex的思想

        当我们在页面上点击一个按钮,它会触发(dispatch)一个action,action随后会执行(commit)一个mutation,mutition会立即改变state,当state改变之后,页面的数据会随之而改变。

状态管理核心状态管理有5个核心:state、getter、mutation、action、module

1.state

        state为单一状态树,在state中需要定义我们所需要管理的数组、对象、字符串等等,只有在这里定义了,在vue.js的组件中才能获取你定义的这个对象的状态。

const state = {
    count: 1
}

    如何在VUE组件中获得Vuex状态

            Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)

npm install vuex --save

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)
const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})

通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到

const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

辅助函数--mapState

        当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性

        当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组

import { mapState } from 'vuex'

computed: {
    ...mapState(['state1', 'state2'])
}

2.getter

        getter有点类似vue.js的计算属性,当我们需要从store的state中派生出一些状态,那么我们就需要使用getter,getter会接收state作为第一个参数,而且getter的返回值会根据它的依赖被缓存起来,只有getter中的依赖值(state中的某个需要派生状态的值)发生改变的时候才会被重新计算。

 Getter 接受 state 作为其第一个参数:

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})

Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:

  注意,getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的

store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

Getter 也可以接受其他 getter 作为第二个参数:

getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}
store.getters.doneTodosCount // -> 1

可以很容易地在任何组件中使用它:

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

通过方法访问

         通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果

辅助函数 -- mapGetters 

mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

import { mapGetters } from 'vuex'

computed: {
    ...mapGetters(['doneTodosCount', 'anotherGetter',])
}

3.mutation

更改store中state状态的唯一方法就是提交mutation,就很类似事件。每个mutation都有一个字符串类型的事件类型和一个回调函数,我们需要改变state的值就要在回调函数中改变。我们要执行这个回调函数,那么我们需要执行一个相应的调用方法:store.commit。

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})
store.commit('increment')

提交载荷(Payload)

可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}


store.commit('increment', 10)

在大多情况下,载荷是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读

mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}

使用常量替代 Mutation 事件类型

使用常量替代 mutation 事件类型在各种 Flux 实现中是很常见的模式。这样可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然

const api = {
    state: {
        account: 'admin'
    },
    mutations:{
        SET_ACCOUNT: (state, account) {
            state.account = account
        }
    }
}

export default api;

Mutation 必须是同步函数

       因为当 mutation 触发的时候,回调函数还没有被调用,devtools 不知道什么时候回调函数实际上被调用——实质上任何在回调函数中进行的状态的改变都是不可追踪的

在组件中提交 Mutation

       可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为`this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

4.action

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

        action可以提交mutation,在action中可以执行store.commit,而且action中可以有任何的异步操作。在页面中如果我们要用这个action,则需要执行store.dispatch

示例,涉及到调用异步 API 和分发多重 mutation

actions: {
  checkout ({ commit, state }, products) {
    // 把当前购物车的物品备份起来
    const savedCartItems = [...state.cart.added]
    // 发出结账请求,然后乐观地清空购物车
    commit(types.CHECKOUT_REQUEST)
    // 购物 API 接受一个成功回调和一个失败回调
    shop.buyProducts(
      products,
      // 成功操作
      () => commit(types.CHECKOUT_SUCCESS),
      // 失败操作
      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
  }
}

在组件中分发 Action

在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

组合 Action

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

调用

store.dispatch('actionA').then(() => {
  // ...
})

如果需在actions中获取state中定义的数据,需用rootState

state: {
    lang: 'zh'//语言设置
},
actions: {
    setLang({commit, rootState}) {
        let locationLang = rootState.lang
    }
}

5.module

module其实只是解决了当state中很复杂臃肿的时候,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    moduleA,
    moduleB
  }
})

store.state.moduleA // -> moduleA 的状态
store.state.moduleB // -> moduleB 的状态

项目结构

Vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:

  1. 应用层级的状态应该集中到单个 store 对象中。

  2. 提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。

  3. 异步逻辑都应该封装到 action 里面。

我在项目中的应用:

└──store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── getters.js        # 根级别的计算属性
    └── modules
        ├── user.js       # 用户信息state状态管理
        └── permission    # 菜单以及权限

index.js

import Vue from 'vue';
import Vuex from 'vuex';
import user from './modules/user';
import permission from './modules/permission';
import getters from './getters';

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {		
    user,//用户的信息
    permission
  },
  getters: getters	//对以上数据进行加工
});

export default store;

getters.js

const getters = {
  uid: state => state.user.uid,     //用户id
  routerPath: state => state.user.routerPath, //路由重定向
  userInfo: state => state.user.userInfo,//用户所有信息
  
  //菜单
  permission_routers: state => {
    // 对应permission.js中的state.routers
    return state.permission.routers;
   }, 
   //权限
   permission_perms: state => {
    // 对应permission.js中的state.perms
    return state.permission.perms;
   }, 
  addRouters: state => state.permission.addRouters
};
export default getters

user.js

import Cookies from 'js-cookie';
import { Message } from 'element-ui';
import instance from 'src/global/http';
import Base64 from '../../../static/base64';
const user = {
    state: {
        uid: "", //用户名
        password: "", //密码
        routerPath: Cookies.get('routerPath'), //路由重定向
        userInfo: null, //用户信息
    },
    mutations: {
        //设置用户ID
        SET_UID: (state, uid) => {
            state.uid = uid;
        },
        //设置密码
        SET_PWD: (state, password) => {
            state.password = password;
        },
        //设置路由重定向的路由
        SET_PATH: (state, routerPath) => {
            state.routerPath = routerPath;
        },
        //设置userInfo
        SET_USERINFO: (state, userInfo) => {
            state.userInfo = userInfo;
        },
    },
    actions: {
        Login({commit}, userInfo) {
            retuen new Promise((resolve, reject) => {
                instance.post('/proxy/auth/login', userInfo).then(res => {
                    if(res.status == 200 && res.data.success) {
                        Cookies.set('userName', userInfo.account, {expires: 14,path: ''}); //设置token
                        Cookies.set('refresh', true); //设置是否刷新参数refresh
                        if(userInfo.checked) {
                            let base = new Base64();
                            let basePassWord = base.encode(userInfo.password); //base64加密设置密码
                            Cookies.set('password', basePassWord, {expires: 14,path: ''}); 
                            commit('SET_PWD', userInfo.password); //修改密码
                        } else {
                            Cookies.set('password', ''); //设置密码
                            commit('SET_PWD', ''); //修改密码
                        }
                        commit('SET_UID', userInfo.account); //修改用户
                        resolve(); //异步操作成功
                    } else {
                        reject(res.data.errorMsg);
                        // Message.error(res.data.errorMsg);
                    }
                }).catch(error => {});
            })
        }
    }
}

export default user;

permission.js

const permission = {
  state: {
    routers:null,//菜单
    perms:null,//权限
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.routers = routers;
    },
    SET_PERMS: (state, perms) => {
      state.perms = perms;
    }
  },
  actions: {
    //c菜单
    GenerateRoutes({ commit }, data) {
      console.log('该用户所有的菜单:',data);
      return new Promise(resolve => {
        commit('SET_ROUTERS', data); 
        resolve();
      })
    },
    //按钮权限
    GeneratePerms({ commit }, data) {
      console.log('该用户下所有权限',data);
      return new Promise(resolve => {
        commit('SET_PERMS', data); 
        resolve();
      })
    }
  }
};
export default permission;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值