VueX 基本使用(vue状态管理)及简单小实例

1、安装vuex依赖包

npm install vuex --save

2、导入vuex包

import Vuex from 'vuex'
Vue.use(Vuex)

3、创建 store 对象

export default new Vuex.Store({
  // state 中存放的就是全局共享的数据
  state: {
    count: 0
  }
})

4、将 store 对象挂载到 vue 实例中

new Vue({
  el: '#app',
  render: h => h(App),
  router,
  // 将创建的共享数据对象,挂载到 Vue 实例中
  // 所有的组件,就可以直接用 store 中获取全局的数据了
  store
})

VueX:状态管理

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

核心模块:State、Getters、Mutations、Actions、Module

(1)、State:

State 提供唯一的公告数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储。我们需要保存的数据就保存在这里,可以在页面通过 this.$store.state来获取我们定义的数据。
// 创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
   state: {
      count: 0
   }
})

组件访问 Store 中数据的第一种方式:

this.$store.state.全局数据名称

组件访问 Store 中数据的第二种方式:

// 1.从 vuex 中按需导入 mapState 函数
import { mapState } from 'vuex'

通过刚才导入的 mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性:

// 2.将全局数据,映射为当前组件的计算属性
computed: {
    ...mapState(['count'])
}

(2)、Getters:

Getter相当于vue中的computed计算属性,不会修改 state 里的源数据,只起到一个包装器的作用,将 state 里的数据变一种形式然后返回出来。getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算,这里我们可以通过定义vuex的Getter来获取,Getters 可以用于监听、state中的值的变化,返回计算后的结果。

① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
② Store 中数据发生变化,Getter 包装出来的数据也会跟着变化。

定义:

// 定义 Getter
const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    showNum: state => {
      return '当前最新的数量是【'+ state.count +'】'
    }
  }
})

使用 getters 的第一种方式:

this.$store.getters.名称

使用 getters 的第二种方式:

import { mapGetters } from 'vuex'

computed: {
  ...mapGetters(['showNum'])
}

(3)、Mutations:

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,只有 mutation 里的函数才有权利去修改 state 中的数据。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。但是,mutation只允许同步函数,不能写异步的代码

①只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。
②通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

定义:

// 定义 Mutation
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add (state) {
      // 变更状态
      state.count++
    }
  }
})

第一种触发方式:

// 触发 mutation
methods: {
    handleAdd () {
      // 触发 mutations 的第一种方式
      this.$store.commit('add')
    }
}

还可以在触发 mutations 时传递参数:

// 定义 Mutation
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    addN (state, step) {
      // 变更状态
      state.count += step
    }
  }
})

第一种触发方式:

// 触发 mutation
methods: {
    handleAdd () {
      this.$store.commit('addN', 3)
    }
}

触发 mutations 的第二种方式:

// 1.从 vuex 中按需导入 mapMutations 函数
import { mapMutations } from 'vuex'

通过刚才导入的 mapMutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:

// 2.将指定的 mutations 函数,映射为当前组件的methods 函数:
methods: {
   ...mapMutations({'add', 'addN'})
}

注意:不要在 mutations 函数中,执行异步操作。所以就需要用到了 Action 用于处理异步任务。 

(4)、Actions:

官方并不建议我们直接去修改store里面的值,而是让我们去提交一个actions,在actions中提交mutation再去修改状态值。可以异步操作。

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

定义:

// 定义 Action
const store = new Vuex.Store({
  // ...省略其他代码
  mutations: {
    add (state) {
      state.count++
    }
  },
  actions: {
    addAsync (context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000)
    }
  }
})

第一种方式触发:

// 触发 Action
methods: {
  handleAdd () {
      // 触发 actions 的第一种方式
      this.$store.dispatch('addAsync')
  }
}

注意:在 actions 中,不能直接修改 state 中的数据,必须通过 context.commit() 触发某个 mutations 的函数才行。

触发 actions 异步任务时携带参数: 

定义:

// 定义 Action
const store = new Vuex.Store({
  // ...省略其他代码
  mutations: {
    addN (state, step) {
      state.count += step
    },
  },
  actions: {
    addNAsync (context, step) {
      setTimeout(() => {
        context.commit('addN', step)
      }, 1000)
    }
  }
})

触发:

// 触发 Action
methods: {
  handleAdd () {
      // 在调用 dispatch 函数,触发 actions 时携带参数
      this.$store.dispatch('addNAsync', 5)
  }
}

触发 actions 的第二种方式: 

// 1.从 vuex 中按需导入 mapActions 函数
import { mapActions } from 'vuex'

通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:

// 2.将指定的 actions 函数,映射为当前组件的 methods 函数
methods: {
  ...mapActions(['addAsync', 'addNAsync'])
}

(5)、Module

Vuex 允许我们将store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。

简要介绍各模块在流程中的功能:

  • Vue Components:Vue 组件。HTML 页面上,负责接收用户操作等交互行为,执行 dispatch 方法触发对应 action 进行回应。
  • dispatch:操作行为触发方法,是唯一能执行 action 的方法。
  • actions:操作行为处理模块,由组件中的$store.dispatch('action 名称', data1)来触发。然后由 commit()来触发 mutation 的调用 , 间接更新 state。负责处理 Vue Components 接收到的所有交互行为。包含同步/异步操作,支持多个同名方法,按照注册的顺序依次触发。向后台 API 请求的操作就在这个模块中进行,包括触发其他 action 以及提交 mutation 的操作。该模块提供了 Promise 的封装,以支持 action 的链式触发。
  • commit:状态改变提交操作方法。对 mutation 进行提交,是唯一能执行 mutation 的方法。
  • mutations:状态改变操作方法,由 actions 中的commit('mutation 名称')来触发。是 Vuex 修改 state 的唯一推荐方法。该方法只能进行同步操作,且方法名只能全局唯一。操作之中会有一些 hook 暴露出来,以进行 state 的监控等。
  • state:页面状态管理容器对象。集中存储 Vue components 中 data 对象的零散数据,全局唯一,以进行统一的状态管理。页面显示所需的数据从该对象中进行读取,利用 Vue 的细粒度数据响应机制来进行高效的状态更新。
  • getters:state 对象读取方法。图中没有单独列出该模块,应该被包含在了 render 中,Vue Components 通过该方法读取全局 state 对象。

下面写个简单的小实例,方便大家理解VueX:

1、首先在store/index.js里定义state:

state: {
    Count: 0 //数值
},

2、新建一个test.vue文件:

<template>
<div>
    <h3>Count的值:{{this.$store.state.Count}}</h3>
</div>
</template>

这时候运行,页面上就得到了这个count值为0。

3、在store/index.js里通过getters新建getStateCount方法接收一个参数state,这个参数就是我们用来保存数据的那个对象Count;

getters: {
    getStateCount(state) {
      return state.Count + 1; //返回Count值
    }
}

4、修改test.vue文件

<template>
<div>
    <h3>Count的值:{{this.$store.state.Count}}</h3>
    <h3>从Getters获取计算后的值:{{this.$store.getters.getStateCount}}</h3>
</div>
</template>

这时在页面显示:

5、在页面下面添加2个按钮,分别可以增加1、减少1:

修改test.vue页面:

<template>
<div>
    <h3>Count的值:{{this.$store.state.Count}}</h3>
    <h3>从Getters获取计算后的值:{{this.$store.getters.getStateCount}}</h3>
    <div>
        <button @click="addCount">+</button>
        <button @click="delCount">-</button>
    </div>
</div>
</template>

<script>
export default {
    methods: {
         addCount:function(){
            this.$store.commit("changAdd");
        },
        delCount:function(){
            this.$store.commit("changDel");
        },
    }
}
</script>

6、因为修改store中的值唯一的方法就是提交mutation来修改,所以在store/index.js里添加mutations,在mutations中定义两个函数,用来对count加1和减1

mutations: {
    changAdd(state) {
       state.Count = state.Count + 1;
    },
    changDel(state) {
       state.Count = state.Count - 1;
    }
},

这时可以在页面上点击+、- 按钮操作数据:

小bug:Count到0的时候点击-还可以减1为-1,所以修改下代码:

changDel(state) {
      if (state.Count == 0) return;
      state.Count = state.Count - 1;
}

OK,现在可以完美实现功能。

但是,官方并不建议我们这样直接去修改store里面的值,而是让我们去提交一个actions,在actions中提交mutation再去修改状态值,接下来我们修改store/index.js文件

7、先定义actions提交mutation的函数:

actions: {
    changAddCount(content) {
       content.commit("changAdd");
    },
    changDelCount(content) {
       content.commit("changDel");
    }
}

8、然后我们去修改test.vue文件:

methods: {
      addCount:function(){
           //this.$store.commit("changAdd");
           this.$store.dispatch("changAddCount")
      },
      delCount:function(){
           //this.$store.commit("changDel");
           this.$store.dispatch("changDelCount")
      },
}

这里我们把commit提交mutations修改为使用dispatch来提交actions;现在我们点击页面,效果是一样的。

好了,我们这里已经实现了一个基本的vuex修改状态值的完整流程。如果我们需要指定加减的数值,那么我们直接传入dispatch中的第二个参数,然后在actions中的对应函数中接受参数在传递给mutations中的函数进行计算:

9、修改mutations和actions:

mutations: {
    changAdd(state) {
       state.Count = state.Count + 1;
    },
    changDel(state, n) {
       if (state.Count == 0) return;
       state.Count = state.Count - n;
    }
},
actions: {
    changAddCount(content) {
       content.commit("changAdd");
    },
    changDelCount(content, n) {
       content.commit("changDel", n);
    }
}

10、修改test.vue页面:

methods: {
      addCount:function(){
           //this.$store.commit("changAdd");
           this.$store.dispatch("changAddCount")
      },
      delCount:function(){
           //this.$store.commit("changDel");
           var n = 2;
           this.$store.dispatch("changDelCount", n)
      },
}

这个时候我们再去点击“ - ”按钮就会发现不再是减1了,而是减去2了。

这次到1的时候会减为-1,继续修改:

changDel(state, n) {
    if (state.Count == 0) {
        return;
    } else if (state.Count == 1) {
        state.Count = state.Count - 1;
    } else {
        state.Count = state.Count - n;
    }
}

OK,功能实现了,最终减到0为止。

辅助函数mapState

当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键。

首先要在页面中构建:

<!-- <h3>Count的值:{{this.$store.state.Count}}</h3> -->
<h3>Count的值:{{Count}}</h3>

<script>
//在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
//当然也可以一起构建
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'; 
export default {
   computed: mapState({
      // 箭头函数可使代码更简练
      Count: state => state.Count,
   })
}
</script>

对象展开运算符:可以简化写法

<!-- <h3>Count的值:{{this.$store.state.Count}}</h3> -->
<h3>Count的值:{{Count}}</h3>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex';
export default {
    computed: { //计算属性
        ...mapState(['Count']), //用...展开运算符把Count展开在资源属性里
    },
};
</script>

效果当然是一样的。

mapMutations, mapActions, mapGetters 也一样可以通过...简写:
<h3>Count的值:{{Count}}</h3>
<h3>从Getters获取计算后的值:{{getStateCount}}</h3>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex';
export default {
    computed: { //计算属性
        ...mapState(['Count']),
        ...mapGetters(['getStateCount']),
    },
    methods: {
        ...mapMutations(['changAdd','changDel']),
        ...mapActions({
            addCount: 'changAddCount',
        }),
        delCount:function(){
            var n = 2;
            this.changDelCount(n);
        },
        ...mapActions({
            changDelCount: "changDelCount",
        }),
    }
};
</script>
原文地址:https://www.cnblogs.com/joe235/p/12029071.html