目录
为vue.js应用程序开发的状态管理模式
采用集中式存储管理应用的所有组件状态
以相应的规则保证以一种可预测的方式发生变化
1. State: 包含了store中存储的各个状态。
2. Getters: 类似于 Vue 中的计算属性,根据其他 getter 或 state 计算返回值。
3.Mutations: 一组方法,是改变store中状态的执行者,只能是同步操作。
4. Actions: 一组方法,其中可以包含异步操作。
在index.js中
- export default new Vuex.Store({
- state: {
- gender:1,
- libai:{
- name:"李白",
- role:"诗人",
- nick:"诗仙",
- age:18
- }
- }
- })
在自己创建的vue中
- <template>
- <div>
- <p>{{$store.state.libai.name}}</p>
- <p>{{$store.state.libai.role}}</p>
- <p>{{$store.state.libai.nick}}</p>
- <p>{{$store.state.libai.age}}</p>
- </div>
- </template>

- mutations: {
- addLiBaiAge(state,n){
- state.libai.age+=n;
- },
- },
- <template>
- <div>
- <button @click="addAge(1)">age+1</button>
- <button @click="addAge(5)">age+5</button>
- <button @click="addAge(10)">age+10</button>
- </div>
- </template>
- methods:{
- addAge(n){
- // this.$store.state.libai.age++;
-
- // 通过commit触发事件,从而修改vuex中的数据
- this.$store.commit("addLiBaiAge",n);
- }
- }
- methods:{
- addAgeAsync(n){
- // 使用dispath触发actions里的函数
- this.$store.dispatch("addAge",n);
- }
- }
- actions: {
- addAge(context,n){
- setTimeout(()=>{
- // 触发mutations的函数
- context.commit("addLiBaiAge",n)
- },1000)
- }
- },
这里actions的使用也同样需要mutations。
- <template>
- <div>
- <p>{{$store.getters.showAge}}</p>
- </div>
- </template>
- getters: {
- showAge(state){
- return "李白今年"+state.libai.age+"岁"
- }
- }