vue:vuex中mapState、mapGetters、mapActions輔助函數及Module的使用


一、普通store中使用mapState、mapGetters輔助函數:

在src目錄下建立store文件夾:

index.js如下:

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={//要設置的全局訪問的state對象 showFooter: true, changableNum:0 count: 0 //要設置的初始屬性值 }; const getters = { //實時監聽state值的變化(最新狀態) isShow(state) { //方法名隨意,主要是來承載變化的showFooter的值 return state.showFooter }, getChangedNum(){ //方法名隨意,主要是用來承載變化的changableNum的值 return state.changebleNum } }; const mutations = { show(state) { //自定義改變state初始值的方法,這里面的參數除了state之外還可以再傳額外的參數(變量或對象); state.showFooter = true; }, hide(state) { //同上 state.showFooter = false; }, newNum(state,sum){ //同上,這里面的參數除了state之外還傳了需要增加的值sum state.changableNum+=sum; } }; const actions = { hideFooter(context) { //自定義觸發mutations里函數的方法,context與store 實例具有相同方法和屬性 context.commit('hide'); }, showFooter(context) { //同上注釋 context.commit('show'); }, getNewNum(context,num){ //同上注釋,num為要變化的形參 context.commit('newNum',num) } }; const store = new Vuex.Store({ state, getters, mutations }); export default store; 

vue提供了注入機制,就是把我們的store 對象注入到根實例中。vue的根實例就是 new Vue構造函數,然后在所有的子組件中this.$store 來指向store 對象。在index.js 中,我們用export store把store已經暴露出去了,然后直接在main.js中引入store並注入store即可。

// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import App from './App' import router from './router/router.js' import store from './store' import echarts from 'echarts' Vue.config.productionTip = false Vue.use(ElementUI) Vue.use(echarts) Vue.prototype.$echarts = echarts /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' }) 

子組件中的computed屬性是根據它的依賴自動更新的,所以只要store中的state發生變化,它就會自動變化,在一般情況下子組件中獲取store中屬性的方式如下:

<template>
 <div>
  <h3>Count is {{某屬性}}</h3>
 </div>
</template>
<script>
 export default {
  computed: {
   count () {
    return this.$store.state.某屬性
   }
  }
 }
</script>

通過computed屬性可以獲取到狀態值,但是組件中每一個屬性(如:count)都是函數,如果有10個,那么就要寫10個函數,且重復寫10遍return this.$store.state不是很方便。vue 提供了mapState函數,它把state直接映射到我們的組件中。

當然使用mapState之前要先引入它,它兩種用法,或接受一個對象,或接受一個數組,其中使用對象的方式又有三種方法。

對象用法如下:

<script>
 import {mapState} from "vuex"; // 引入mapState export default {   // 下面這三種寫法都可以 computed: mapState({ // 箭頭函數可使代碼更簡練 count: state => state.count, // 傳字符串參數 'count' 等同於 `state => state.count` countAlias: 'count', // 為了能夠使用 `this` 獲取局部狀態,必須使用常規函數 countPlusLocalState (state) { return state.count + this.localCount } }) } </script>

當映射的計算屬性的名稱與state的子節點名稱相同時,我們也可以給 mapState傳一個字符串數組。

<script>
 import {mapState} from "vuex"; export default { computed: mapState([ // 數組 "count" ]) } </script>

如果我們組件內部也有computed屬性怎么辦?它又不屬於mapState,我們可以使用es6中的對象分割語法,把mapState函數生成的對象再分割成一個個的,就像最開始的時候我們一個一個羅列計算屬性,有10個屬性,我們就寫10個函數。

<script>
 import {mapState} from "vuex"; export default { computed: { ...mapState([ "count" ]), getValue(){ return 1; } } } </script>

二、Module中使用mapState、mapGetters、mapActions輔助函數:

在src目錄下建立store文件夾:

其中:

collection.js

//collection.js const state={ collects:['hi'], //初始化一個colects數組 field: '空天作戰任務規划' }; const getters={ }; const mutations={ }; const actions={ }; export default { namespaced:true,//用於在全局引用此文件里的方法時標識這一個的文件名 state, getters, mutations, actions } 

footerStatus.js:

//footerStatus.js const state={ //要設置的全局訪問的state對象 name: 'beautiful', address: 'Hunan Changsha', school: '國防科大', showFooter: true, changableNum:0 //要設置的初始屬性值 }; const getters = { //實時監聽state值的變化(最新狀態) }; const mutations = { changeSchool(state, value){ state.school = value; } }; const actions = { _changeSchool(context, value){ context.commit('changeSchool', value) } }; export default { namespaced: true, //用於在全局引用此文里的方法時標識這一個的文件名 state, getters, mutations, actions } 

index.js:

import Vue from 'vue' import Vuex from 'vuex' import collection from './modules/collection' import footerStatus from './modules/footerStatus' Vue.use(Vuex) export default new Vuex.Store({ modules: { collection, footerStatus } }) 

假如我們想在組件中使用module中的state、getters、mutations、actions,那該如何使用呢?

除了和普通store一樣需要在main.js中注入store外,具體方法如下:

<template>
  <div>
    <p>name: {{name}}</p>
    <p>school: {{school}}</p>
    <p>address: {{address}}</p>
    <p>field: {{field}}</p>
    <p>arrList: {{arrList}}</p>
    <div><button @click="changeSchool()">改變值</button></div>
  </div>
</template>

<script>
  import {mapState, mapGetters} from 'vuex'
  export default {
    data(){
      return {
        use: 'vuex高級使用方法'
      }
    },
    computed: {
      ...mapState({
        name: state => state.footerStatus.name,
        address(state){
          return state.footerStatus.address;
        }
      }),
      ...mapState('footerStatus', {
        school: 'school'
      }),
      ...mapState('collection', ['field']),
      _use(){
        this.use;
      },
      ...mapGetters('collection', {
        arrList: 'renderCollects'
      })
    },
    methods: {
      changeSchool(){
        this.$store.dispatch("footerStatus/_changeSchool", '北大');
      }
    }
  }
</script>

<style scoped>

</style>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM