1. 程式人生 > 其它 >vuex中的mapState、mapGetters、mapMutations、mapActions

vuex中的mapState、mapGetters、mapMutations、mapActions

vuex中的mapState、mapGetters、mapMutations、mapActions

1.state

state相當於vue中的data,通過state來存放狀態

vuex:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: { //存放狀態
    name:'Bob',
    age:20
  },
  mutations: {},
  actions: {},
  modules: {}
})

vue:

<h1>{{$store.state.name}}</
h1
>

也可以在computed計算屬性中來獲得

<template>
  <div class="home">
    {{nickname}}
  </div>
</template>
<script>
export default {
  name: 'home',
  computed:{
    nickname(){
      return this.$store.state.name
    }
  }
}
</script>

還可以使用mapState輔助函式將store中的屬性對映過來

<template>
  <div class="home">
    {{name}}
  </div>
</template>
import {mapState} from 'vuex'
export default {
  name: 'home',
  computed: mapState(['name','age','gender'])...mapState(['nickname','age','gender'])
}

注意:使用mapstate輔助函式的時候,前面的方法名和獲取的屬性名是一致的

2.getter

getter相當於vue中的計算屬性,通過getters的到想要的值,第一個引數就是state

Vue.use(Vuex)
export default new Vuex.Store({
  state: { //存放狀態
    nickname:'Simba',
    firstname:'張',
    lastname:'三豐',
    age:20,
    gender:'男',
    money:1000
  },
  getters:{
    realname(state){
      return state.firstname+state.lastname
    },
    money_us(state){
      return (state.money/7).toFixed(2)
    }
  },
  mutations: {},
  actions: {},
  modules: {}
})

vue:

computed: {  //computed是不能傳引數的
 valued(){
   return this.value/7
 },
 ...mapGetters(['realname','money_us'])
}
3.Mutation

相當於vue中的method方法,mutation需要在vue中通過commit來呼叫裡面的方法,第一個引數是state,第二個是額外的引數

mutations: { //類似於methods
  addAge(state,payLoad){
     state.age+=payLoad.number
  }
}
<div class="home">
   <div><button @click="test">測試</button></div>
</div>
methods:{
 test(){
   this.$store.commit('addAge',{
     number:5
   })
 }
}

使用mapMutations

methods:{
 ...mapMutations(['addAge'])
}

使用的時候可以直接用addAge方法,如果需要引數,也可以直接傳參