[前端开发]Vuex的状态管理

Vuex是专门为Vue.js开发的状态管理模式

  • 集中式管理
  • 状态管理工具(单一状态树)
  • 当多个组件同时需要访问一个变量时,组件之间互相传递过于麻烦,就可以用Vuex来把这些变量来集中起来
  • 如登陆的状态、个人信息、地理位置、收藏夹购物车等等

核心概念

  • State:数据及单一状态树
  • Getters:类似组件的计算属性computed
  • Mutations:存放方法
  • Actions做异步操作
  • Modules:划分模块数据保存

用法和vue-router差不多
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state:{
    counter:1000
  },
  mutations:{},
  actions:{},
  getters:{},
  modules:{}
})

export default store
  • 之后在main.js里引用一下就可以使用了
<h2>{{$store.state.counter}}</h2>
<button @click="$store.state.counter++">+</button>
<button @click="$store.state.counter--">-</button>
  • 但是官方并不推荐这样修改,如果不通过mutations修改state,数据无法追踪,最好能通过mutations(方法)
const store = new Vuex.Store({
  state:{
    counter:1000
  },
  mutations:{
    increment(state){
      state.counter++
    },
    decrement(state){
      state.counter--
    }
  }
}
  • 使用时,通过commit提交到mutations
<button @click="add">+</button>
<button @click="minus">-</button>


methods:{
    add(){
      this.$store.commit('increment')
    },
    minus(){
      this.$store.commit('decrement')
    }
  }

getters的一些操作

  getters:{
    powerCounter(state){
      return state.counter * state.counter
    },
    get23stu(state){
      return state.students.filter(stu=> stu.age >22)
    },
    get23stuLength(state,getters){
      return getters.get23stu.length
    },
    //传参
    getAgeStu(state){
      return age=>{
        return state.students.filter(s=>s.age===age)
      }
    }
  }

Mutations

  • Vuex的store状态更新的唯一方式:提交mutations
mutations:{
    increment(state){
      state.counter++
    },
    decrement(state){
      state.counter--
    },
    //传参
    incrementCount(state,count){
      state.counter += count
    },
    addStu(state,stu){
      state.students.push(stu)
    }
  }
  
  <h2>年龄大于22的人数共有{{$store.getters.get23stuLength}}</h2>
    <h2>getters传参数,年龄等于22的人</h2>
    <h2>{{$store.getters.getAgeStu(22)}}</h2>
    
addCount(count){
      this.$store.commit('incrementCount',count)
    },
    addStu(){
      const stu = {id:123,name:'test',age:35}
      this.$store.commit('addStu',stu)
    }
  • 用set在state响应式修改属性
    <h2>---修改info的字段---</h2>
    <h2>{{$store.state.info}}</h2>
    <button @click="updateInfo">添加</button>
    
    updateInfo(){
      this.$store.commit('updateInfo')
    }
    
    updateInfo(state){
      Vue.set(state.info,'address','HangZhou-ZheJiang')
    }
  • 用delete响应式删除属性
Vue.delete(state.info,'age')

在写mutations的时候,会发现很多相似的名字很容易写错,此时可以定义一个常量,创建一个文件来保存这些常量

  • mutations-type.js
export const INCREMENT = 'increment'
  • 在app.vue和 index.js里修改对应代码
import {
  INCREMENT
} from './store/mutations-type'
//引入
add(){
      this.$store.commit(INCREMENT)
    },
mutations:{
    [INCREMENT](state){
      state.counter++
    },
}

Action 做异步操作

  • 当进行异步操作时,mutations无法进行响应监听
  • 举个例子,做一个定时器,里面修改info里的属性的值,用actions来做
  • app.vue
updateInfo(){
      // this.$store.commit('updateInfo')
      //用dispatch来传入到actions
      this.$store.dispatch('aUpdateInfo')
    }
  • index.js
actions:{
//同样的,actions里也不能直接更改state
//通过commit提交到mutations来更改state
    aUpdateInfo(context){
      setTimeout(() => {
        context.commit('updateInfo')
      }, 1000);
    }
  }
//Mutations:
updateInfo(state){
      state.info.name = '异步操作actions'
    }

modules

  • 子模块获取父模块state
//rootState
getCount(state,getters,rootState){
    return state.name+rootState.counter
    //将名字和数字拼接起来
}

高级用法

mapGetters,mapActions的使用
import { mapActions } from 'vuex'
methods:{
    ...mapActions(['addCart']),
    this.addCart(product).then(res=>{
        console.log(res);
        
      })
      // this.$store.dispatch('addCart',product).then(res=>{
      //   console.log(res)
      // })
//不使用mapActions时的写法
}
//mapGetters用法同上
  • //传actions,用了mapActions后
  • 上面直接调用映射的addCart时,vuex内部就会做dispatch这个操作
mapGetters,mapACtions的2种写法
...mapActions:{
    add:'addCart'
}
// 这样写在调用时就可以直接this.add()来使用
//Vue内部会映射到actions里的addCart

...mapActions(['addCart'])
posted @ 2020-04-01 15:55  kaba  阅读(201)  评论(0编辑  收藏  举报