vuex的輔助函數(shù)

https://www.cnblogs.com/samve/p/10726629.html


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

vue提供了注入機(jī)制,就是把我們的store 對象注入到根實(shí)例中。vue的根實(shí)例就是 new

Vue構(gòu)造函數(shù),然后在所有的子組件中this.$store 來指向store 對象。在index.js 中,我們用export

store把store已經(jīng)暴露出去了,然后直接在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.importVuefrom'vue'importElementUIfrom'element-ui'import'element-ui/lib/theme-chalk/index.css'importAppfrom'./App'importrouterfrom'./router/router.js'importstorefrom'./store'importechartsfrom'echarts'


一、普通store中使用mapState、mapGetters輔助函數(shù):

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

?

index.js如下:

importVuefrom'vue';importVuexfrom'vuex';Vue.use(Vuex);conststate={//要設(shè)置的全局訪問的state對象showFooter:true,changableNum:0count:0//要設(shè)置的初始屬性值};constgetters = {//實(shí)時監(jiān)聽state值的變化(最新狀態(tài))isShow(state) {//方法名隨意,主要是來承載變化的showFooter的值returnstate.showFooter? },? getChangedNum(){//方法名隨意,主要是用來承載變化的changableNum的值returnstate.changebleNum? }};constmutations = {? show(state) {//自定義改變state初始值的方法,這里面的參數(shù)除了state之外還可以再傳額外的參數(shù)(變量或?qū)ο?;state.showFooter =true;? },? hide(state) {//同上state.showFooter =false;? },? newNum(state,sum){//同上,這里面的參數(shù)除了state之外還傳了需要增加的值sumstate.changableNum+=sum;? }};constactions = {? hideFooter(context) {//自定義觸發(fā)mutations里函數(shù)的方法,context與store 實(shí)例具有相同方法和屬性context.commit('hide');? },? showFooter(context) {//同上注釋context.commit('show');? },? getNewNum(context,num){//同上注釋,num為要變化的形參context.commit('newNum',num)? }};conststore =newVuex.Store({? state,? getters,? mutations});exportdefaultstore;

vue提供了注入機(jī)制,就是把我們的store 對象注入到根實(shí)例中。vue的根實(shí)例就是 new

Vue構(gòu)造函數(shù),然后在所有的子組件中this.$store 來指向store 對象。在index.js 中,我們用export

store把store已經(jīng)暴露出去了,然后直接在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.importVuefrom'vue'importElementUIfrom'element-ui'import'element-ui/lib/theme-chalk/index.css'importAppfrom'./App'importrouterfrom'./router/router.js'importstorefrom'./store'importechartsfrom'echarts'Vue.config.productionTip =falseVue.use(ElementUI)Vue.use(echarts)Vue.prototype.$echarts = echarts/* eslint-disable no-new */newVue({el:'#app',? router,? store,components: { App },template:'<App/>'})

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

Count is {{某屬性}}

<script>

export default {

? computed: {

? count () {

? ? return this.$store.state.某屬性

? }

? }

}

</script>

通過computed屬性可以獲取到狀態(tài)值,但是組件中每一個屬性(如:count)都是函數(shù),如果有10個,那么就要寫10個函數(shù),且重復(fù)寫10遍return

this.$store.state不是很方便。vue 提供了mapState函數(shù),它把state直接映射到我們的組件中。

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

對象用法如下:

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

當(dāng)映射的計(jì)算屬性的名稱與state的子節(jié)點(diǎn)名稱相同時,我們也可以給 mapState傳一個字符串?dāng)?shù)組。

import{mapState}from"vuex";exportdefault{computed: mapState([// 數(shù)組"count"]) }

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

import{mapState}from"vuex";exportdefault{computed: {? ? ? ...mapState(["count"]),? ? ? getValue(){return1;? ? ? ? }? ? } }

二、Module中使用mapState、mapGetters、mapActions輔助函數(shù):

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

?

其中:

collection.js

//collection.jsconststate={collects:['hi'],//初始化一個colects數(shù)組field:'空天作戰(zhàn)任務(wù)規(guī)劃'};constgetters={};constmutations={};constactions={};exportdefault{namespaced:true,//用于在全局引用此文件里的方法時標(biāo)識這一個的文件名state,? getters,? mutations,? actions}

footerStatus.js:

//footerStatus.jsconststate={//要設(shè)置的全局訪問的state對象name:'beautiful',address:'Hunan Changsha',school:'國防科大',showFooter:true,changableNum:0//要設(shè)置的初始屬性值};constgetters = {//實(shí)時監(jiān)聽state值的變化(最新狀態(tài))};constmutations = {? changeSchool(state, value){? ? state.school = value;? }};constactions = {? _changeSchool(context, value){? ? context.commit('changeSchool', value)? }};exportdefault{namespaced:true,//用于在全局引用此文里的方法時標(biāo)識這一個的文件名state,? getters,? mutations,? actions}

index.js:

importVuefrom'vue'importVuexfrom'vuex'importcollectionfrom'./modules/collection'importfooterStatusfrom'./modules/footerStatus'Vue.use(Vuex)exportdefaultnewVuex.Store({modules: {? ? collection,? ? footerStatus? }})

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

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

name: {{name}}

school: {{school}}

address: {{address}}

field: {{field}}

arrList: {{arrList}}

改變值

<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>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • ### store 1. Vue 組件中獲得 Vuex 狀態(tài) ```js //方式一 全局引入單例類 // 創(chuàng)建一...
    蕓豆_6a86閱讀 794評論 0 3
  • 姓名:岳沁 學(xué)號:17101223458 轉(zhuǎn)載自:http://blog.csdn.net/h5_queensty...
    丘之心閱讀 2,219評論 0 1
  • 安裝 npm npm install vuex --save 在一個模塊化的打包系統(tǒng)中,您必須顯式地通過Vue.u...
    蕭玄辭閱讀 3,054評論 0 7
  • Vuex 是什么? Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有...
    skycolor閱讀 933評論 0 1
  • ### store 1. Vue 組件中獲得 Vuex 狀態(tài) ```js //方式一 全局引入單例類 // 創(chuàng)建一...
    蕓豆_6a86閱讀 446評論 0 0

友情鏈接更多精彩內(nèi)容