1. Vuex是适用于Vue.js应用的状态管理库,为应用中的所有组件提供集中式的状态存储与操作,保证了所有状态以可预测的方式进行修改。

2. 安装:

1> script引入 

1 <script src="vuex.js"></script>

2> npm:

npm install vuex

 store/index.js文件中

 1 import Vue from 'vue'
 2 import Vuex from 'vuex'
 3 
 4 Vue.use(Vuex);
 5 const store = new Vuex.Store({
 6   // 状态管理:类似于vue中的data   
 7   state: {  
 8     data: 'title'
 9   },
10   // 专用于修改state中的数据,通过commit触发
11   mutations: {
12     changeDataMT(state,params){
13       state.data = params
14     }
15   },
16   // 异步操作:通过dispatch触发
17   actions: {
18     changeDataAC(context,params){
19       let {commit} = context;
20       setTimeout(()=>{
21         commit('changeDataMT',params)
22       },2000)
23     }
24   },
25   // 计算属性:需要return
26   getters: {
27     changeDataGT(state){
28       return state.data.up
29     }
30   },
31 })
32 export default store;

 

 在组件里使用:

 1 组件1:
 2 <template>
 3 
 4   <div class="about">
 5 
 6     <h1>我是组件1</h1>
 7 
 8     <h3>浏览器中此处会显示data的值: {{ $store.state.data }}</h3>
 9 
10     <button @click="pageChangeData1">改数据MT</button>
11 
12     <button @click="pageChangeData2">改数据AC</button>
13 
14     <h3>{{$store.getters.changeDataGT}}</h3>
15 
16   </div>
17 
18 </template>
19 
20 <script>
21 
22 export default {
23 
24   data() {
25 
26     return {};
27 
28   },
29 
30   methods: {
31 
32     pageChangeData1() {
33 
34       // 通过commit触发mutaion并传参
35 
36       // console.log(this.$store);
37 
38       this.$store.commit('changeDataMT',20)
39 
40     },
41 
42     pageChangeData2(){
43 
44       this.$store.dispatch('changeDataAC','两秒之后我就变成这个样子')
45 
46     }
47 
48 
49   },
50 
51 };
52 
53 </script>
54 
55 组件2:
56 <template>
57   <div class="about">
58     <h1>我是组件2</h1>
59     <h3>浏览器中此处会显示data的值{{$store.state.data}}</h3>
60   </div>
61 </template>
62 
63 <script>
64 export default {
65   
66 };
67 </script>

3.  结果:

 

4. 不要忘记在main.js中:

1 import store from 'store'
2 new Vue({
3   store:store, 
4   render: h => h(App),
5 }).$mount('#app')