vuex官网的解释是:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的全部组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
下面介绍在vue脚手架中简单应用vuex来实现组件之间传递数据,固然组件之间传递能够使用emit,但页面组件愈来愈多涉及到数据传递就愈来愈麻烦,vuex的便利性就体现出来。javascript
先上图看看简单的案例(没写样式,将就看吧),主页homepage组件点击按钮"获取城市列表",跳转到城市列表组件citylist,在列表中点击对应的城市后,返回主页并将数据传递给主页显示出来。html
一般设计store对象都包含4个属性:state,getters,actions,mutations。
如何理解这4个属性呢,从本身的话来理解:vuestate (相似存储全局变量的数据)
getters (提供用来获取state数据的方法)
actions (提供跟后台接口打交道的方法,并调用mutations提供的方法)
mutations (提供存储设置state数据的方法)且看官方的一个示例图:
从上图能够很好看出这几个属性之间的调用关系(不过官方图没有画出getters的使用)
能够看出:java
- 组件Vue Component经过dispatch来调用actions提供的方法
- 而actions除了能够和api打交道外,还能够经过commit来调mutations提供的方法
- 最后mutaions将数据保存到state中
- 固然,Vue Components还以经过getters提供的方法获取state中的数据
因此store.js的代码能够设计成:git
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); let store = new Vuex.Store({ // 1. state state:{ city:"城市名" }, // // 2. getters getters:{ // 参数列表state指的是state数据 getCityFn(state){ return state.city; } }, // 3. actions // 一般跟api接口打交道 actions:{ // 设置城市信息 // 参数列表:{commit, state} // state指的是state数据 // commit调用mutations的方法 // name就是调用此方法时要传的参数 setCityName({commit,state}, name){ // 跟后台打交道 // 调用mutaions里面的方法 commit("setCity", name); } }, // 4. mutations mutations:{ // state指的是state的数据 // name传递过来的数据 setCity(state, name){ state.city = name;//将传参设置给state的city } } }); export default store;
就能够在组件使用this.$store来调用方法github
import store from './store/store.js';
组件页面中的city数据经过this.$store.getters来获取store.js所写getters提供的getCityFn方法vuex
<template> <div class="home"> <h1>{{city}}</h1> <!-- 按钮导航 --> <router-link tag='button' to="/citylist">获取城市列表</router-link> </div> </template>
<script> export default { data () { return { } }, computed:{ city:function() { // 经过vuex的getters方法来获取state里面的数据 return this.$store.getters.getCityFn; } } } </script>
当点击列表的时候,经过this.$store.dispatch来调用store.js中actions所提供的setCityName方法,并将城市名传参过去shell
<template> <div class="city"> <ul> <li v-for="(item,index) in cityArr" @click="backFn(index)"> <h2>{{item}}</h2> </li> </ul> </div> </template>
<script> export default { name: 'HelloWorld', data () { return { cityArr:['北京','上海','广州','深圳','茂名','张家界','清远','汕头','佛山'] } }, methods:{ backFn : function(index){ // 调用vuex的ations设置城市的值 this.$store.dispatch("setCityName", this.cityArr[index]); //返回到首页 this.$router.push("/"); } } } </script>
最后完成如开头案例演示的效果
固然若是涉及大量数据,建议参考官方推荐的 目录文件结构设计:
还有 官网案例
├── index.html ├── main.js ├── api │ └── ... # 抽取出API请求 ├── components │ ├── App.vue │ └── ... └── store ├── index.js # 咱们组装模块并导出 store 的地方 ├── actions.js # 根级别的 action ├── mutations.js # 根级别的 mutation └── modules ├── cart.js # 购物车模块 └── products.js # 产品模块
最后附上这个vuex简单使用代码 demo