接上篇~
5.最后一种,互通:无所谓父组件或者是子组件,而是随时随地都能调用到数据的一种方法。便是利用vuex来管理数据,官网描述:
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
可以理解为vuex为全局的数据管理系统。最核心的几步操作:
在vuex文件夹下新建store.js文件,
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); const store = new Vuex.Store({ // 定义状态 state: { owner: 'Han Meimei' },
mutations:{
newOwner(state,msg){
state.owner = msg;
}
}
});
export default store;
在状态存储系统中保存一个名为”owner”的状态;
footer.vue:
header.vue:
最终在父组件App.vue中调用:
实现效果:
后序:
刚开始接触vue的时候,就知道vuex是全局存储数据状态的管理系统,但是在潜意识中总是告诉自己,这个貌似很复杂,不太好理解。再加之工作中也没用到vuex组件,于是也就将其搁置了,直到现在在重新拾起来好好学习的时候,才意识到它并没有想象当中的“难”。
或许,一直拥有“初生牛犊不怕虎”的精神会做成很多“大事”。
![1_thumb[24] 1_thumb[24]](https://images2015.cnblogs.com/blog/934768/201706/934768-20170614154104993-1325581190.png)
![2_thumb[20] 2_thumb[20]](https://images2015.cnblogs.com/blog/934768/201706/934768-20170614154109103-1272010544.png)
![1_thumb[29] 1_thumb[29]](https://images2015.cnblogs.com/blog/934768/201706/934768-20170614154113462-2039510942.png)
![2_thumb[24] 2_thumb[24]](https://images2015.cnblogs.com/blog/934768/201706/934768-20170614154115587-256042485.png)
![1_thumb[32] 1_thumb[32]](https://images2015.cnblogs.com/blog/934768/201706/934768-20170614154119306-683717819.png)
![2_thumb[29] 2_thumb[29]](https://images2015.cnblogs.com/blog/934768/201706/934768-20170614154122009-906336143.png)
![3_thumb[7] 3_thumb[7]](https://images2015.cnblogs.com/blog/934768/201706/934768-20170614154338243-563082561.gif)
![5_thumb[4] 5_thumb[4]](https://images2015.cnblogs.com/blog/934768/201706/934768-20170614154126400-1014906768.png)