1.vuex的作用
vuex是专门为Vuejs应用程序设计的状态管理工具。其实是集中的数据管理仓库。相当于数据库mongoDB等,任何组件都可以存取仓库中的数据。
vuex的组成部分:
- state:是存储的基本数据。
- mutations:提交更改数据。
- getter:对state加工,和computed计算属性一样。
- actions:处理异步,通过store.commit方法触发mutations中的方法,从而改变state值。
- module:是store分割的模块,每个模块拥有自己的state、mutations、getters、actions。
2.vuex流程和vue对比
vue中的data、methods、computed,可以实现响应式。
视图通过点击事件,触发methods中的方法,更改data的值,一旦数据发生变化,computed中的函数把数据能更新到视图。那么computed是如何更新的?其实就是vue的双向绑定原理了。
computed中的计算属性getter生成唯一的watcher—>访问computed中的方法时,会将Dep.target指向它的watcher–>在方法中访问this.。。。,会调用get方法,新增watcher到dep中—>设置时,会调用set方法触发dep.notify实现视图更新。
1.那vuex和vue的响应式例子有什么关系?
我们也可以通过vuex实现同样的功能。vuex中的四部分与vue的对应关系:
state--->data、mutations--->methods、getters--->computed、actions
:为了处理异步,不能直接更新state,需要借助mutations。
2.dispatch、commit又是做什么的呢?
在vue中,我们触发点击事件,就能触发methods中的方法,这是vue设计好的。而在vuex中则不行了,一定要有个东西来触发才行。①通过dispatch可以触发可以触发actions中的方法,②actions中的commit可以触发mutations中的方法。从而实现state的更新。
vuex实现响应式的例子:
//store.js
const store = new Vuex.Store({
state: {
count: 0
},
//第三步:改变state值,state的值只能通过mutations来修改
mutations: {
increment(state) {
state.count++
}
},
//第二步:this.$store.commit("increment")触发mutations中函数"increment"
actions: {
increment({commit}) {
commit("increment"); //this.$store.commit("increment")
}
},
//第四步:通过getter中的方法来获取state值
getters: {
getCount(state) {
return state.count
}
}
})
export default store
//App.vue
<template>
<div id="app">
<button @click="increment">增加</button>
{{this.$store.getters.getCount}}
</div>
</template>
<script>
export default {
methods: {
increment(){
//第一步:this.$store.dispatch("increment")触发actions函数"increment"
this.$store.dispatch("increment")
}
}
}
</script>
3.vuex的原理
vuex吸收了redux的各种优点,完美的结合了vue的响应式数据。那么它的原理是什么呢?
1.每一个vue的插件,都需要一个公开的install
方法,vuex也不例外。
// src/store.js
export function install (_Vue) {
if (Vue && _Vue === Vue) {
return
}
Vue = _Vue
applyMixin(Vue)//在所有组件的beforeCreate注入了设置this.$store这样的一个对象,
//在任意组件中执行this.$store都能找到store对象
}
2.Vuex.Store的构造函数中,有一堆初始化以及resetStoreVM(this,state)
整个vuex的关键。
// src/store.js
function resetStoreVM (store, state, hot) {
// 省略无关代码
Vue.config.silent = true
//本质:将我们传入的state作为一个隐藏的vue组件的data
//也就是说,我们的commit操作,本质上其实是修改这个组件的data
store._vm = new Vue({
data: {
$$state: state
},
computed
})
}
//this.$store._vm.$data.$$state===this.$store.state
总结:
- vuex是针对vuejs的状态管理工具。vuex完美的结合了vue的响应式数据。
- vue可以直接触发methods中的方法,vuex不行。为了处理异步,当你触发一个点击事件时,会通过
dispatch
来访问actions中的方法,actions中的commit
会触发mutations中的方法从而修改state的值,通过getters来把数据反映到视图。 - vuex通过
Vue.use(vuex)
,从而调用install
方法,通过applyMixin(Vue)
在任意组件执行this.$store
都能访问到store对象,实现将store挂载注入到组件中。 - vuex的state状态是响应式的,是借助vue的data是响应式,将state存入vue实例组件的data中。
- vuex的getters则是借助于vue的计算属性computed实现数据的实时监听。
参考文档:http://www.imooc.com/article/291242
https://www.jianshu.com/p/d95a7b8afa06
https://www.cnblogs.com/tg666/p/11532587.html