一、vuex是什么
- vuex是vue的一个库(插件)
- 作用:对vue应用中的多个组件的共享状态进行集中式的管理(读/写)
二、使用(单向数据流)
-
state
- vuex中的数据源,我们需要保存的数据都存储在这里,在页面中可以通过
this.$store.state
来获取 - 状态对象是唯一的
// state const state = { uid: undefined, // 用户Id nickname: undefined, // 用户昵称 } // 使用 this.$store.state.uid this.$store.state.nickname
- vuex中的数据源,我们需要保存的数据都存储在这里,在页面中可以通过
-
getters
- Getters相当于vue中的computed计算属性,getters的返回值会被缓存,只有当他所依赖的值发生改变,getters值才会重新计算。
- 作用: Getters可以用来监听state中的值的变化
const getters = { isEnable: state => state.app.isEnable, uid: state => state.user.uid, // 用户Id nickname: state => state.user.nickname, // 用户昵称 }
-
mutations (不推荐使用)
- 修改state中数据的唯一方法(函数)
// mutations const mutations = { SET_UID: (state, uid) => { // state是上面定义的state对象 // uid可选参数 state.uid = uid; }, SET_NICKNAME: (state, nickname) => { state.nickname = nickname; } } // 调用 this.$store.commit('updateUid', uid) ```
-
actions (推荐)
- 更新状态的方法(在actions中通过提交mutations完成 – dispatch)
const actions = { setUID({ commit }, uid) { commit('SET_UID', uid); }, setNickname({ commit }, nickname) { commit('SET_NICKNAME', nickname); } }
作用
多组件间的数据共享(共享状态)
使用
vuex的核心管理对象模块:store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state, // 状态对象
mutations, // 包含多个更新state函数的对象
actions, // 包含多个对应事件回调函数的对象
getters // 包含多个getter计算属性函数的对象
})
状态管理创建了之后需要全局映射使用
// main.js
import store from './store'
new Vue({
el:'#app',
components:{App},
template:'<APP/>',
store // 所有组件对象都多了一个属性:$store
})
store对象
- 所有用vuex管理的组件中都多了一个属性$store,它就是一个store对象
- 属性 : state–>注册的state对象
getters --> 注册的getters对象 - 方法:this.$store.dispatch(actionsName,data) 分发调用actions
store应用
import {mapState, mapGetters,mapActions} from 'Vuex'
computed:{
...mapState(['xxx','xxx'])
//mapState的返回值:
{
count(){
return this.$store.state['count']
}
}
...maoGetters(['xxx']) //mapGetters的返回值:
{xxx(){return this.$store.getters['xxx']}}
}
methods:{
...mapActions(['xxxx'])
}
vuex原理图