vuex简单介绍

一、什么是vuex
vuex是vue的状态管理模式
项目中需要共享一些数据,vux就是把这些数据集中管理起来的容器,这些数据就叫做状态,比如一个用户的用户名,性别,权限等

二、vuex的核心概念

  1. 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 ’
})
}

  1. 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 ’
])
}

  1. 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 ’
])
}

  1. 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’
])
}

  1. 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 })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vuex是Vue.js应用程序开发的状态管理库,它能够帮助我们更好地组织和管理Vue应用程序中的状态。Vuex的核心概念是store,它类似于一个全局的容器,存储着应用程序中的各种状态(state),并提供了一些方法(mutations、actions、getters)来访问和操作这些状态。 下面是一个简单Vuex示例,假设我们有一个计数器应用程序,需要实现加和减功能: 1. 首先,安装Vuex并在main.js中引入: ```javascript import Vuex from 'vuex' Vue.use(Vuex) ``` 2. 创建一个store并定义初始状态: ```javascript const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ }, decrement(state) { state.count-- } }, actions: { incrementAsync({commit}) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount(state) { return state.count } } }) ``` 3. 在组件中使用store: ```javascript <template> <div> <p>Count: {{count}}</p> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="incrementAsync">+ Async</button> </div> </template> <script> export default { computed: { count() { return this.$store.getters.getCount } }, methods: { increment() { this.$store.commit('increment') }, decrement() { this.$store.commit('decrement') }, incrementAsync() { this.$store.dispatch('incrementAsync') } } } </script> ``` 在上面的示例中,我们定义了一个状态count和三个方法increment、decrement和incrementAsync,分别用来增加、减少和异步增加计数器的值。我们还定义了一个getter来获取当前的计数器值。在组件中,我们通过computed属性来获取count值,并通过methods属性来调用对应的方法,其中commit方法用来提交一个mutation来修改状态,dispatch方法用来触发一个action来异步修改状态。 以上就是Vuex的使用核心和一个简单案例。如果您还有其他的问题,欢迎继续向我提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值