关于vue.js:vuex-的那些事

4次阅读

共计 1934 个字符,预计需要花费 5 分钟才能阅读完成。

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;是带有命名空间的模块,使模块更具备封装性和复用性,}

 
});
正文完
 0