vuex是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。下图:

以上是一个表示“单向数据流”理念的示意图,View视图上的用户操作反应到Actions上,Actions改变数据源State,View以声明的方式将state反映到视图上。
注:在上篇文章中新建的vue工程的基础上增加vuex功能
1.npm安装Vuex

2.安装 Vuex 之后,让我们来新建一个store文件夹(这个不是必须的),并在文件夹下新建index.js文件,文件中引入我们的vue和vuex。在一个模块化的打包系统中,您必通过 Vue.use() 进行引用:

这步操作结束,vuex就算引用成功了。
3.可以在main.js文件中在实例化 Vue对象时加入 store 对象,这可以把store的实例注入所有的子组件中,如下图所示:

4.现在我们看store文件夹下的index.js里需要怎么新建store。

如上图所示,用export default 封装代码,可以让外部引用。
当store对象比较复杂时,可以把store分割成模块(module),import导入分割过得store,在modules中引用。testStore就是分割过的store,现在我们testStore.js文件里增加一个常量对象state,加入一个改变state的方法changeCount。

5.在components文件夹下新建一个vue的模板,名字叫test.vue。在模板中引入mapState, mapMutations, mapActions。

此时就可以运行代码,完成vuex的简单使用,运行结果如图:

1就是testStore中的count值,点击增加触发Actions,调用改变数据源state的方法changeCount使count值增加,state的值反映到视图上,相应的1就会增加。
mapState
state对象赋值给内部对象,也就是把stroe中的值,赋值给我们模板里data中的值,可以通过mapState的对象来赋值,首先要用import引入mapState,然后在computed计算属性里写如上代码,使用ES6的箭头函数来给count赋值。
mapMutations
mutations是同步修改状态,在模板test.vue里用import 引入我们的mapMutations,在<\script>标签里添加methods属性,并加入mapMutations,引入mutations中的方法,就可以在button的click事件直接使用了。
mapActions
actions是异步修改状态,和mapMutations使用方式一样,在模板test.vue里用import 引入我们的mapActions,在<\script>标签里添加methods属性,并加入mapActions,引入actions中的方法,就可以在button的click事件直接使用了。
网友评论