1、下载vuex的组件库依赖
npm install --save vuex
2、使用vuex的基本步骤:
1、创建一个Vuex.Store
2、在Vue中注册store对象
3、在vue组件中通过this.$store.dispatch('xxx')调用store.js中的actions对象中的xxx方法
3、上代码
①、App.vue
<template><!-- 这是一个计数器 --> <div> <p>click {{$store.state.count}} times, count is {{evenOrOdd}}</p> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="incrementIfAdd">increment if add</button> <button @click="incrementAsync">increment async</button> </div></template><script>export default { computed:{ evenOrOdd(){ return this.$store.getters.evenOrOdd } }, methods: { increment(){ //通知vuex去增加 this.$store.dispatch('increment') //触发store中对应的action }, decrement(){ //通知vuex去减少 this.$store.dispatch('decrement') //触发store中对应的action }, incrementIfAdd(){ //通知vuex this.$store.dispatch('incrementIfAdd') //触发store中对应的action }, /* 过1s才增加 */ incrementAsync(){ //通知vuex this.$store.dispatch('incrementAsync') //触发store中对应的action }, }}</script><style></style>
②、store.js
/* vuex的核心管理对象模块: store */import Vuex from "vuex";import Vue from "vue";Vue.use(Vuex);/* 状态对象 */const state = { //初始化状态 count: 0};/* 多个更新state函数的对象 */const mutations = { //增加的mutation INCREMENT(state) { state.count++; }, //减少的mutation DECREMENT(state) { state.count--; }};/* 多个对应事件回调函数的对象 */const actions = { //增加的action increment({ commit }) { //提交增加的mutation commit("INCREMENT"); }, decrement({ commit }) { //提交减少的mutation commit("DECREMENT"); }, //带条件的 incrementIfAdd({ commit, state }) { if (state.count % 2 === 1) { //提交增加的mutation commit("INCREMENT"); } }, //异步的action incrementAsync({ commit }) { //在action中直接可以执行异步代码 setTimeout(() => { //提交增加的mutation commit("INCREMENT"); }, 1000); }};/* 计算属性函数的对象 */const getters = { evenOrOdd(state) { return state.count % 2 === 0 ? "偶数" : "奇数"; }};export default new Vuex.Store({ state, mutations, actions, getters});
③、main.js
import Vue from 'vue'import App from './App.vue'import store from './store'new Vue({ el: '#app', store, //所有组件对象都多一个属性:$store components: { App }, template: '<App/>'})
3、说明一下调用流程,以App.vue中的methods#increment方法为例:
increment通过this.$store.dispatch('increment')
调用store中的action;
actions中的increament通过commit传入了INCREMENT,commit会去调用mutations的INCREMENT函数,mutations会更新state的状态,最后页面显示也会跟着变化。