上一篇 vuex其实超简单,只需3步 简单介绍了vuex的3步入门,不过为了初学者容易消化,我削减了不少内容,这一节,就是把少掉的内容补上, 若是你没看过上篇,请戳连接过去先看一下再回来,不然,你会以为本文摸不着头脑.前端
纯属我的经验,不免有不正确的地方,若有发现,欢迎指正!
仍是同样,本文针对初学者.vue
1、 Gettergit
咱们先回忆一下上一篇的代码github
computed:{
getName(){
return this.$store.state.name
}
}
复制代码
这里假设如今逻辑有变,咱们最终指望获得的数据(getName),是基于 this.$store.state.name
上通过复杂计算得来的,恰好这个getName要在好多个地方使用,那么咱们就得复制好几份.vuex
vuex 给咱们提供了 getter,请看代码 (文件位置 /src/store/index.js
)缓存
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// 相似 vue 的 data
state: {
name: 'oldName'
},
// 相似 vue 的 computed -----------------如下5行为新增
getters:{
getReverseName: state => {
return state.name.split('').reverse().join('')
}
},
// 相似 vue 里的 mothods(同步方法)
mutations: {
updateName (state) {
state.name = 'newName'
}
}
})
复制代码
而后咱们能够这样用 文件位置 /src/main.js
bash
computed:{
getName(){
return this.$store.getters.getReverseName
}
}
复制代码
事实上, getter 不止单单起到封装的做用,它还跟vue的computed属性同样,会缓存结果数据, 只有当依赖改变的时候,才要从新计算.app
2、 actions和$dispatch异步
细心的你,必定发现我以前代码里 mutations
头上的注释了 相似 vue 里的 mothods(同步方法)
模块化
为何要在 methods
后面备注是同步方法呢? mutation只能是同步的函数,只能是同步的函数,只能是同步的函数!! 请看vuex的解释:
如今想象,咱们正在 debug 一个 app 而且观察 devtool 中的 mutation 日志。每一条 mutation 被记录, devtools 都须要捕捉到前一状态和后一状态的快照。然而,在上面的例子中 mutation 中的异步函数中的回调让这不 可能完成:由于当 mutation 触发的时候,回调函数尚未被调用,devtools 不知道何时回调函数实际上被调 用——实质上任何在回调函数中进行的状态的改变都是不可追踪的。
那么若是咱们想触发一个异步的操做呢? 答案是: action + $dispatch, 咱们继续修改store/index.js下面的代码
文件位置 /src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// 相似 vue 的 data
state: {
name: 'oldName'
},
// 相似 vue 的 computed
getters:{
getReverseName: state => {
return state.name.split('').reverse().join('')
}
},
// 相似 vue 里的 mothods(同步方法)
mutations: {
updateName (state) {
state.name = 'newName'
}
},
// 相似 vue 里的 mothods(异步方法) -------- 如下7行为新增
actions: {
updateNameAsync ({ commit }) {
setTimeout(() => {
commit('updateName')
}, 1000)
}
}
})
复制代码
而后咱们能够再咱们的vue页面里面这样使用
methods: {
rename () {
this.$store.dispatch('updateNameAsync')
}
}
复制代码
3、 Module 模块化
当项目愈来愈大的时候,单个 store 文件,确定不是咱们想要的, 因此就有了模块化. 假设 src/store
目录下有这2个文件
moduleA.js
export default {
state: { ... },
getters: { ... },
mutations: { ... },
actions: { ... }
}
复制代码
moduleB.js
export default {
state: { ... },
getters: { ... },
mutations: { ... },
actions: { ... }
}
复制代码
那么咱们能够把 index.js
改为这样
import moduleA from './moduleA'
import moduleB from './moduleB'
export default new Vuex.Store({
modules: {
moduleA,
moduleB
}
})
复制代码
这样咱们就能够很轻松的把一个store拆分红多个.
4、 总结
store
对象,而 getters 和 mutations 的参数是 state
.若是以为本文对您有用,请给本文的github加个star,万分感谢
另外,github上还有其余一些关于前端的教程和组件,有兴趣的童鞋能够看看,大家的支持就是我最大的动力。