一、什么是vuex
vuex是vue的状态管理模式
项目中需要共享一些数据,vux就是把这些数据集中管理起来的容器,这些数据就叫做状态,比如一个用户的用户名,性别,权限等
二、vuex的核心概念
- state
定义:
new Vuex.Store( {
state:{
token: ’ ',
todos: [
{ id: 1, text: ’ … ', done: true },
{ id: 2, text: ’ … ’ , done: false}
]
}
} )
在vue组件中使用:
a. 直接调用
this.$store.state.token
b. 通过计算属性,直接用{{ token }}或者this.token就能调用
computed:{
token( ){
return this.$store.state.token
}
}
c. 调用mapState
import { mapState } from ’ vuex ’
computed: {
…mapState({
token: state => state.token
})
或者
…mapState({
’ token ’
})
}
- getter
对state进行过滤加工,可以认为是store的计算属性
定义:
Vuex.Store({
getter: {
// state作为第一个参数
doneTodos: state => {
return state.todos.filter( todo => todo.done )
},
// getter作为第二个参数
doneTodoCount: ( state, getters ) => {
return getter.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 }
}
})
在组件中使用geters:
// 直接调用:
this.KaTeX parse error: Expected '}', got 'EOF' at end of input: …{ return this.store.getters.doneTodosCount
}
}
// 或者直接调用mapDetters
import { mapGetters } from ’ vuex ’
computed: {
// getter 属性另取一个名字,使用对象格式
…mapGetters({
doneCount: ’ doneTodosCount ’
})
// 或者mapGetters([
‘doneTodos’,
’ doneTodosCunt ’
])
}
- mutations
在vuex中只能通过提交mutation来修改store中的状态,它是一个同步的过程
定义:
new Vuex.Store({
mutations: {
// state作为第一个参数,接收第二个参数为传入的对象
setToken(state, obj) {
const st = state
st.token = obj
}
}
})
在需要多人协作的大型项目中,使用常量替代mutation事件类型:
// 新建一个mutation-types.js
export const SET_token = ’ SET_token '// 设置token
// store.js
import { SET_TOKEN } from ’ ./mutation-types ’
new Vuex.Store({
mutations: {
// state作为第一个参数,接收第二个参数为传入的对象
[ SET_TOKEN ] ( state, obj ) {
const st = state
st.token = obj
}
}
})
在vue组件中使用
// 直接调用
this.$store.commit (’ setToken ', obj)
// 在methods里使用mapMutatios, 就可以@click = " setToken "来调用
methods: {
…mapMutatios({
setToken:'SET_token'
})
//或者
…mapMutatioss([
’ setToken ',
’ SET_TOKEN ’
])
}
- action
通过调用 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())
}
},
})
在vue组件中使用:
// 直接调用
this.$store.dispatch(‘login’, obj)
// 调用 action 中的异步操作,并处理
this.KaTeX parse error: Expected '}', got 'EOF' at end of input: … => { this.message.success(‘登录成功!’)
val && this.$router.push(‘home’)
}).catch(err => {
console.log('登录错误: ', err)
})
// 在 methods 里使用 mapActions,就可以 @click=“login(obj)” 来调用
import { mapActions } from ‘vuex’
methods: {
…mapActions({
login: ‘login’
})
// 或者
…mapActions([
‘login’
])
}
- 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
}
})
在vue组件中使用:
默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的,只有state注册在自己的模块内,调用需要加上模块名。调用的方式:
// state
computed: {
…mapState({
userInfo: state => state.user.userInfo
})
…mapGetters({
getUser: ‘getUser’
})
}
// getters
this.
s
t
o
r
e
.
g
e
t
t
e
r
s
.
g
e
t
U
s
e
r
/
/
m
u
t
a
t
i
o
n
s
t
h
i
s
.
store.getters.getUser // mutations this.
store.getters.getUser//mutationsthis.store.commit(‘setUser’, obj)
// actions
this.$store.dispatch(‘getUserInfo’, obj)
设置 namespaced: true 使模块具有更高的封装度和复用性。
这时模块内的getter会有第四参数rootGetters,作为访问全局getter:
getters: {
// rootState是根节点状态
getUser (state, getters, rootState, rootGetters) {}
},
actions: {
// rootState是根节点状态
getUserInfo ({ state, commit, rootState, rootGetters }) {}
}
在组件中调用 commit 和 dispatch 时,需要在具体mutation和action前把模块名加上:
// mutations
this.
s
t
o
r
e
.
c
o
m
m
i
t
(
′
u
s
e
r
/
s
e
t
U
s
e
r
′
,
o
b
j
)
/
/
a
c
t
i
o
n
s
t
h
i
s
.
store.commit('user/setUser', obj) // actions this.
store.commit(′user/setUser′,obj)//actionsthis.store.dispatch(‘user/getUserInfo’, obj)
在设置 namespaced: true 子模块内想要调用全局的 mutation 或者 action 时需要将 { root: true } 作为第三参数传给 dispatch 或 commit:
// mutations
commit(‘SET_TOKEN’, obj, { root: true })
// actions
dispatch(‘otherModule/getUserInfo’, obj, { root: true })