likes
comments
collection
share

vuex 的那些事

作者站长头像
站长
· 阅读数 298

vuex 是专门为vue.js 服务的状态管理库(自己的理解就是:为vue框架存储全局的数据,可以在各个局部组件内使用)

特点:

  1. 响应性: store 中状态改变, 在组件中也能高效更新
  2. 改变store状态唯一路径, 通过 mutation 中提交commit,dispatch 方法是调异步函数的

核心:

  1. state 单一状态树——对象: 每个模块可以拥有自己的状态树对象
//在store 中定义
const state = {
   count: 0,
   name: ""
}

mapState 辅助函数:把store中的多个状态映射到局部组件内的计算属性

import { mapState } from 'vuex'
computed: {
   //使用对象展开运算符将此状态混入到局部组件中
    ...mapState(['name']), //名称不变
    ...mapState({firstName: 'name'}]),  //起个别名  
}
  1. getter:状态计算属性对象。 若需要使用store中的多个状态进行计算,得到的值应用到多个组件中, 就可以使用getter, getters可以说成是store 的计算属性

在store中定义

const getters =  {
  // 以属性的方法定义
  doCount1: (state, getters)=> {
    return  "hello " + state.name
  }
 // 以返回带参数的函数方法定义,
  doCount2 :(state, getters)=>(id)=> {
    return  "hello " + state.name + "your id is number " + id
  }
}

访问时使用也略有不同
属性访问: this.$store.getters.doCount1
方法访问: this.$store.getters.doCount2(id)

mapGetters 辅助函数, 把store中的getters 映射到局部组件内的计算属性

import { mapGetters } from 'vuex'
computed: {
   //使用对象展开运算符将此属性混入到局部组件中
    ...mapGetters(['doCount1']),
}
  1. mutations:事件注册对象—— 更改store状态, 不能直接调用,需通过commit 调用
const mutations = {
  UPDATE_COUNT(state, num) {
    state.count = state.count + num
  },
}

mapMutations: 辅助函数, 把 store 中的mutations 映射到局部组件内的计算属性

import { mapMutations } from 'vuex'
methods: {
   //使用对象展开运算符将此方法混入到局部组件中
    ...mapMutations(['UPDATE_COUNT']),
}

****注意,因为mutations 必须是同步函数, 为了解决异步函数, 引入了action, 故 在action中可以包含任意类型的函数使用commit,可以调用mutations 中的函数, 使用dispatch 分发可以调用异步函数见action****

  1. actions
const actions =  {
    increment (context, num) {
      context.commit('UPDATE_COUNT', num)
    }
  }

方法接受一个context 对象, 包含本模块内的state, getters, commit, dispatch(异步分发) 等属性, 但它并不是store实例哦, 可以利用解构参数传入参数 {commit, dispatch}

const actions =  {
    increment ({commit}, num) {
      context.commit('UPDATE_COUNT', num)
    }
  }

mapActions: 辅助函数, 把store中的action 映射到局部组件的method 方法内

import { mapActions } from 'vuex'
methods: {
   //使用对象展开运算符将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
    ...mapActiongs(['increment']),
}

一个完整的store

export default new Vuex.Store({
  state:{
      //存放状态
  },
    getters:{
        //state 的计算属性
  },
  mutations:{
       // 更改state中状态的逻辑 , 同步操作
  },
  actions: {
        // 提交mutations , 异步操作
  },
  modules: {
       // 将store 分成一个个子模块, 每个子模块中拥有自己的state, mutations, actions, modules, 模块内写 namespaced: true;是带有命名空间的模块, 使模块更具有封装性和复用性,
  }

 
});