Vuex状态管理(基础属性理解)

vuex状态管理

在vue中我们可以使用vuex来保存我们需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新。

1. 在src目录下新建一个目录store,在该目录下新建一个index.js的文件,用来创建vuex实例,然后在该文件中引入vue 和 vuex,创建vuex.store实例保存到变量store中,最后export default导出store

const store = new Vuex.Store({})
export default store;

2. 在main.js文件中引入该文件
在文件里面添加 import store from “./store”

new Vue({
el:"#app",
store,
router,
...
})

3. state:
vuex中的数据源,我们需要保存的数据就保存在这里,可以在页面通过this.$store.state来获取我们定义的数据

const store = new Vuex.store({
state :{
count:1  // (比如说这个)
}
})

页面引用

{{this.$store.state.count}}

4. getters:
getters相当于vue中的computed计算属性,getter的返回值会根据他的依赖被缓存起来,且只有当他的依赖值发生了改变才会被重新计算,这里我们可以通过定义vuex的getters来获取,Getters可以用于监听,state中值的变化,返回计算后的结果

页面引用方法

{{this.$store.state.count}}
{{this.$store.getters.getStateCount}}

getStateCount接收一个参数,这个参数就是 我们用来保存数据的那个对象-----》vuex中getters写法如下

getters:{
  getStateCount:function(state){
  return state count + 1
}

5. mutations:
数据在页面获取到了,需要修改count的值,唯一的方法就是提交mutation来修改,在helloworld添加两个按钮,一个加一,一个减一;点击按钮调用addFun(执行加的方法)和 reduction(执行减得方法),然后提交页面的mutation中的方法修改值

count的值:{{this.$store.state.count}}
<button @click="addFun"> + <button>
<button @click="reductionFun"> - <button>

methods:{
addFun() {
  this.$store.commit(‘add’)
},
reductionFun() {
  this.$store.commit(‘reduction’)
}
}  

添加mutation,在mutation中定义两个函数,用来对count加1和减1,就是上面commit提交的两个方法

mutation:{
    add(state){
        state.count = state.count + 1;
    },
    reduction(state){
        state.count = state.count - 1;
    },
} 

6. Actions:

官方并不建议直接去修改store中的值,而是让我们去提交一个actions,在actions中提交mutation再去修改状态值,在index.js里面去修改,定义actions提交mutation的函数

actions:{
    addFun(context){
        context.commit(“add”)
    },
    reductionFun(context){
        context.commit(“reduction”)
    }
}    
methods:{
    addFun(){
        this.$store.dispatch("addFun");
        //this.store.commit("add")
    },
    reductionFun(){
        this.$store.dispatch("reductionFun")
    }
}    

这里把commit提交mutations修改为dispatch来提交actions,效果相同

如果需要指定加减的数值,那么直接传入dispatch的第二个参数,然后在actions中对应的函数中接收参数传递给mutations中的函数进行计算

7. mapState、mapGetters、mapActions、mapMutations辅助函数用法

 import {mapState , mapGetters , mapActions , mapMutations} from 'vuex'

   computed:{
       ...mapState({
           count1:state  => state.count
       }),
     ...mapGetters({
           count1:countNum  //getters中的方法名
       }) 
   },
    methods:{
   ...mapMutations({
      add:"addCount"
    }).
    ...mapActions({
      add:"addCountFun"
    })
    //或者
    ...mapActions(['addA', 'addB']),
  }

 以上就是vuex状态管理最基本的概念

posted @ 2019-09-27 13:59  Judicious  阅读(582)  评论(0编辑  收藏  举报