不管是vue仍是react,不管是rudex仍是vuex,都是服务于产品的需求。html
需求:vue
点击等操做来引起交互react
交互致使数据发生变化vuex
发生的变化反馈给用户(显示在页面上等)api
因此这不是一篇软文,而是一篇操做文。你要具有必定的vue,vuex概念。异步
这里以页面点击为示例。函数
//Index.vue <template> ... <router-link to="/" @click.native="jump" page-index="发现"> </router-link> ... </template> <script> ... methods:{ jump(ev){ this.$store.dispatch({ type:'IBIM_CHANGE', //actions中的函数名 index:ev.currentTarget.getAttribute('page-index') //附带的参数 }) } ... </script>
这个vue组件的代码应该比较简单,就是绑定了一个事件。而后经过this.$store.dispatch
来触发action的操做this
这里描述了如何分发:http://vuex.vuejs.org/zh-cn/a...spa
Action 相似于 mutation,不一样在于:code
Action 提交的是 mutation,而不是直接变动状态。
Action 能够包含任意异步操做。
来自于组件中的dispatch根据type触发对应的action中的函数(这里是IBIM_CHANGE
)
//actions.js import * as types from './mutation-types' export const IBIM_CHANGE = ({ commit }, playload) => { commit(types.IBIM_CHANGE, { index: playload.index }) }
触发了这里的IBIM_CHANGE
函数,而且传递了一个commit
和一个荷载playload
。
因为mutation必须是同步的,在Action咱们能够作异步操做,为获取数据等行为提供了可能。
更改 Vuex 的 store 中的状态的惟一方法是提交 mutation。
//mutations.js export const IBIM_CHANGE = (state, payload) => { state.where = payload.index }
在action中咱们经过commit触发了一个type为IBIM_CHANGE
的mutation,并在回调中更改状态state
。
这里描述了mutations:http://vuex.vuejs.org/zh-cn/m...
//index.js //组装module和根级别的模块并导出 store import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as mutations from './mutations' Vue.use(Vuex) export default new Vuex.Store({ state: { where: '发现' }, actions, mutations })
这里用来导出顶级store,供全局使用。
我将状态where挂载在全局上了(我的以为它在项目组件中的位置不属于任何一个module,是属于全局的)
备注:我这里没有module
下面是点击操做时候的状态变化监控:
简单描述一下能够有哪些属性
Vuex.Store({ state: Object mutations:{ [type: string]: Function } actions: { [type: string]: Function } getters:{ [key: string]: Function } modules: Object plugins:Array<Function>, strict: Boolean })
这里是vuex的具体API:http://vuex.vuejs.org/zh-cn/a...