vuex commit 模块_vuex速记
我已经花那么多时间看文档了,一到面试我还是漏掉一些,忘掉几个概念!啊啊··········所以下方的东西是在抄句子做笔记Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。Vuex 应用的核心就是 store,它包含着你的应用中大部分的状态 (state)。核心概念有五个,但基本上理解三个就可以了!StateGetterMutationActionModuleState尽管State的
我已经花那么多时间看文档了,一到面试我还是漏掉一些,忘掉几个概念!啊啊··········
所以下方的东西是在抄句子做笔记
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
Vuex 应用的核心就是 store,它包含着你的应用中大部分的状态 (state)。
核心概念有五个,但基本上理解三个就可以了!
- State
- Getter
- Mutation
- Action
- Module
State
尽管State的正统解释是“唯一数据源SSOT”,不过我确实可以理解为存放数据的地方。要从其它文件读取里面的数据可以在计算属性返回某个状态。可以通过store.state.data
来得到某个数据,不过这个依赖全局状态单例。还有一种是使用Vue.use(Vuex)
这种注册机制,这种比较适合模块化的构建系统,之后可以通过this.$store
访问到store的实例。
上面说计算属性可以拿到store实例的状态,不过如果需要的状态过多可以用mapState
辅助函数,可以少声明一些。(更多用法看文档去)
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
Getter
就像是计算属性一样,可以在里面定义一些方法来更新state里的状态,而且官方也希望这么做。
Getter 接受 state 作为其第一个参数,也接受其他getter作为第二个参数:
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
}
之后在其它文件可以用this.$store.getters
来访问到,当然这里也可以用上mapGetter
辅助函数。
Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。就像是vue文件的methods方法一样,在里面定义一些方法,接受一个state参数。
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
要在其它文件里触发mutations,不能直接通过属性方式来访问并执行,要调用该方法this.$store.commit('increment')
。commit可以提交额外的参数,它叫载荷,你要在定义的时候记得处理它。commit方法耶支持对象风格的提交方式,这是整个对象都为载荷,例如:
store.commit({
type: 'increment',
amount: 10
})
挡在其它组件使用mutations时,可以在Methods或某个生命周期里等使用this.$store.commit()
,但也可以使用mapMutations
辅助函数(根节点要注入store为前提)
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
Action
action可以说是异步的mutation操作,不过提交的是mutation。
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用context.commit
提交一个 mutation,或者通过context.state
和context.getters
来获取 state 和 getters。
actions: {
increment (context) {
context.commit('increment')
}
}
//或者这样,利用解构赋值
actions: {
increment ({ commit,state,getters }) {
commit('increment')
}
}
action在其它文件要用this.$store.dispatch
的方法来触发,注意返回的是promise对象,适合的场景有调用异步 API和分发多重 mutation等。 不过也可以使用mapActions
辅助函数将组件的 methods 映射为store.dispatch
调用(也需要根节点注入store
)
Module
这个只是将一个大的store实例分解成不同的小store实例模块,每个小store实例会有自己的状态和完整的方法,会有一些小区别,例如之前mutation的state对象是指模块的局部状态对象。另外还有命名空间,对于此不是特别了解,所以这里就此作罢吧!
更多推荐
所有评论(0)