一、vuex的定义
1.Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
2.如果项目较小,简单的store就可以了
如果项目属于中大型的单页应用,可以考虑在组件外部对状态进行管理,即使用vuex
二、获取store对象方法
1.在vue2中使用this.$store.xxx拿到属性
2.在vue3中setup是在beforeCreated和created之前执行,此时vue对象并未创建,则没有this。故使用vuex中的usestory方法
import { useStore } from 'vuex' // 引入useStore 方法
const store = useStore() // 该方法用于返回store 实例
console.log(store) // store 实例对象
三、五大核心
1.state:
单一状态树:每个应用将仅仅包含一个 store 实例。(不建议在state直接进行数据变化的操作)用于存放数据
state:{
name:'1',
password:'1'
}
使用$store.state.xxx获取
2.mutations
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation(每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数)
mutations: {
// 传入 state
increment (state) {
state.count++
}
}
第一种提交方法:在vue3中,可以直接使用store.committ(‘increment’,需要传递的参数)
这个传递的参数,即 mutation 的载荷(payload)
第二种提交方法:提交 mutation 的另一种方式是直接使用包含 type 属性的对象:
const add = (num) => {
store.commit({
type: 'increment ', // 类型就是mution中定义的方法名称
num
})
}
3.actions(异步)
异步操作在action中进行,再传递到mutation
action 中定义的方法默认参数context 上下文,即为store对象
通过 context 上下文对象,拿到store,通过 commit 触发 mution 中的方法,以此来完成异步操作
actions:{
// context 上下文对象,可以理解为store
increment_action(context,num){
SetTimeout(()=>{
context.commit('increment ',num)// 通过context去触发mutions中的sum
},1000)
}
}
分发操作:
第一种:在template中使用dispatch 来调用定义的increment_action
store.dispatch('increment_action', num)
第二种:以对象形式
store.dispatch({
type: 'increment_action',
num: 10
})
可以再通过 promise 实现异步操作完成,通知组件异步执行成功或是失败。
const addAction = (num) => {
store.dispatch('increment_action', {
num
}).then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
})
}
4.getters类似于计算属性
getters 可以接收两个参数,一个是 state, 一个是自身的 getters ,并对自身存在的方法进行调用
getters: {
more20stu (state, getters) { return getters.more20stu.length}
}
$store.getters.xxx调用
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。
案例:实现年龄筛选
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
在template中可以使用
store.getters.getTodoById(2)
具体可以看
https://www.ab62.cn/article/20746.html
5.modules
vuex允许我们将store分割成模块化(modules),而每个模块拥有着自己的state、mutation、action、getters等
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = createStore({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
在template中模块中的写法和无模块的写法大同小异,带上模块的名称即可
// user.js模块
// 导出
export default{
namespaced:true,
state:()=>({
token:localStorage.getItem('token') || ''
}),
mutations:{
setToken(state,token){
state.token=token
localStorage.setItem('token',token)
}
},
action:{
}
}
最终通过 store/index.js 中进行引入
// store/index.js
import { createStore } from 'vuex'
import user from './modules/app.js'
export default createStore({
modules: {
app
}
})
<h2>{{$store.state.app.token}}</h2>
store.commit('app/increment', num) // 参数带上模块名称
store.dispatch('app/increment_action', increment)