vuex入門(mén)文檔

如果你在使用 vue.js , 那么我想你可能會(huì)對(duì) vue 組件之間的通信感到崩潰 摹迷。

我在使用基于 vue.js 2.0 的UI框架 ElementUI 開(kāi)發(fā)網(wǎng)站的時(shí)候 , 就遇到了這種問(wèn)題 : 一個(gè)頁(yè)面有很多表單 , 我試圖將表單寫(xiě)成一個(gè)單文件組件 , 但是表單 ( 子組件 ) 里的數(shù)據(jù)和頁(yè)面 ( 父組件 ) 按鈕交互的時(shí)候 , 它們之間的通訊很麻煩 :

<template>
  <div>
    <a href="javascript:;" @click="show = true">點(diǎn)擊</a>
    <t-dialog :show.sync="show"></t-dialog>
  </div>
</template>

<script>
import dialog from './components/dialog.vue'
export default {
  data(){
    return {
      show:false
    }
  },
  components:{
    "t-dialog":dialog
  }
}
</script>


<!--子組件-->
<template>
  <el-dialog :visible.sync="currentShow"></el-dialog>
</template>

<script>
export default {
  props:['show'],
  computed:{
      currentShow:{
          get(){
              return this.show
          },
          set(val){
              this.$emit("update:show",val)
          }
      }
  }
}
</script>

之所以這么麻煩 , 是因?yàn)楦附M件可以通過(guò) props 給子組件傳遞參數(shù) , 但子組件內(nèi)卻不能直接修改父組件傳過(guò)來(lái)的參數(shù)。

這時(shí)候 , 使用 vuex 就可以比較方便的解決這種問(wèn)題了 :

<!--父組件中引入子組件-->
<template>
  <div>
    <a href="javascript:;" @click="$store.state.show = true">點(diǎn)擊</a>
    <t-dialog></t-dialog>
  </div>
</template>

<script>
import dialog from './components/dialog.vue'
export default {
  components:{
    "t-dialog":dialog
  }
}
</script>
<!--子組件-->
<template>
  <el-dialog :visible.sync="$store.state.show"></el-dialog>
</template>

<script>
export default {}
</script>

是不是方便了許多 , 這就是 vuex 最簡(jiǎn)單的應(yīng)用 , 不要被網(wǎng)上其他教程嚇到 , vuex 原來(lái)可以這么簡(jiǎn)單 !

安裝、使用 vuex
首先我們?cè)?vue.js 2.0 開(kāi)發(fā)環(huán)境中安裝 vuex :
npm install vuex --save
然后 , 在 main.js 中加入 :

Vue.use(vuex);
var store = new vuex.Store({//store對(duì)象
    state:{
        show:false
    }
})

再然后 , 在實(shí)例化 Vue對(duì)象時(shí)加入 store 對(duì)象 :

  el: '#app',
  router,
  store,//使用store
  template: '<App/>',
  components: { App }
})

完成到這一步 , 上述例子中的 $store.state.show 就可以使用了踪古。

modules
前面為了方便 , 我們把 store 對(duì)象寫(xiě)在了 main.js 里面 , 但實(shí)際上為了便于日后的維護(hù) , 我們分開(kāi)寫(xiě)更好 , 我們?cè)?src 目錄下 , 新建一個(gè) store 文件夾 , 然后在里面新建一個(gè) index.js :

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);

export default new vuex.Store({
    state:{
        show:false
    }
})

那么相應(yīng)的 , 在 main.js 里的代碼應(yīng)該改成 :

//vuex
import store from './store'

new Vue({
  el: '#app',
  router,
  store,//使用store
  template: '<App/>',
  components: { App }
})

這樣就把 store 分離出去了 , 那么還有一個(gè)問(wèn)題是 : 這里 $store.state.show 無(wú)論哪個(gè)組件都可以使用 , 那組件多了之后 , 狀態(tài)也多了 , 這么多狀態(tài)都堆在 store 文件夾下的 index.js 不好維護(hù)怎么辦 ?

我們可以使用 vuex 的 modules , 把 store 文件夾下的 index.js 改成 :

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);
import dialog_store from '../components/dialog_store.js';//引入某個(gè)store對(duì)象

export default new vuex.Store({
    modules: {
        dialog: dialog_store
    }
})

這里我們引用了一個(gè) dialog_store.js , 在這個(gè) js 文件里我們就可以單獨(dú)寫(xiě) dialog 組件的狀態(tài)了 :

export default {
    state:{
        show:false
    }
}

做出這樣的修改之后 , 我們將之前我們使用的 $store.state.show 統(tǒng)統(tǒng)改為$store.state.dialog.show 即可。

如果還有其他的組件需要使用 vuex , 就新建一個(gè)對(duì)應(yīng)的狀態(tài)文件 , 然后將他們加入 store 文件夾下的 index.js 文件中的 modules 中券腔。

modules: {
    dialog: dialog_store,
    other: other,//其他組件
}

mutations
前面我們提到的對(duì)話(huà)框例子 , 我們對(duì)vuex 的依賴(lài)僅僅只有一個(gè) $store.state.dialog.show 一個(gè)狀態(tài) , 但是如果我們要進(jìn)行一個(gè)操作 , 需要依賴(lài)很多很多個(gè)狀態(tài) , 那管理起來(lái)又麻煩了 !

mutations 登場(chǎng) , 問(wèn)題迎刃而解 :

export default {
    state:{//state
        show:false
    },
    mutations:{
        switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)state
            state.show = state.show?false:true;
            //你還可以在這里執(zhí)行其他的操作改變state
        }
    }
}

使用 mutations 后 , 原先我們的父組件可以改為 :

<template>
  <div id="app">
    <a href="javascript:;" @click="$store.commit('switch_dialog')">點(diǎn)擊</a>
    <t-dialog></t-dialog>
  </div>
</template>

<script>
import dialog from './components/dialog.vue'
export default {
  components:{
    "t-dialog":dialog
  }
}
</script>

使用 $store.commit('switch_dialog')來(lái)觸發(fā) mutations 中的 switch_dialog 方法伏穆。

這里需要注意的是:

mutations 中的方法是不分組件的 , 假如你在 dialog_stroe.js 文件中的定義了
switch_dialog 方法 , 在其他文件中的一個(gè) switch_dialog 方法 , 那么
$store.commit('switch_dialog')會(huì)執(zhí)行所有的 switch_dialog 方法。
mutations里的操作必須是同步的纷纫。
你一定好奇 , 如果在 mutations 里執(zhí)行異步操作會(huì)發(fā)生什么事情 , 實(shí)際上并不會(huì)發(fā)生什么奇怪的事情 , 只是官方推薦 , 不要在 mutationss 里執(zhí)行異步操作而已枕扫。

actions
多個(gè) state 的操作 , 使用 mutations 會(huì)來(lái)觸發(fā)會(huì)比較好維護(hù) , 那么需要執(zhí)行多個(gè) mutations 就需要用 action 了:

export default {
    state:{//state
        show:false
    },
    mutations:{
        switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)state
            state.show = state.show?false:true;
            //你還可以在這里執(zhí)行其他的操作改變state
        }
    },
    actions:{
        switch_dialog(context){//這里的context和我們使用的$store擁有相同的對(duì)象和方法
            context.commit('switch_dialog');
            //你還可以在這里觸發(fā)其他的mutations方法
        },
    }
}

那么 , 在之前的父組件中 , 我們需要做修改 , 來(lái)觸發(fā) action 里的 switch_dialog 方法:

<template>
  <div id="app">
    <a href="javascript:;" @click="$store.dispatch('switch_dialog')">點(diǎn)擊</a>
    <t-dialog></t-dialog>
  </div>
</template>

<script>
import dialog from './components/dialog.vue'
export default {
  components:{
    "t-dialog":dialog
  }
}
</script>

使用 $store.dispatch('switch_dialog')來(lái)觸發(fā) action 中的 switch_dialog 方法。

官方推薦 , 將異步操作放在 action 中辱魁。

getters
getters 和 vue 中的 computed 類(lèi)似 , 都是用來(lái)計(jì)算 state 然后生成新的數(shù)據(jù) ( 狀態(tài) ) 的烟瞧。

還是前面的例子 , 假如我們需要一個(gè)與狀態(tài) show 剛好相反的狀態(tài) , 使用 vue 中的 computed 可以這樣算出來(lái) :

computed(){
    not_show(){
        return !this.$store.state.dialog.show;
    }
}

那么 , 如果很多很多個(gè)組件中都需要用到這個(gè)與 show 剛好相反的狀態(tài) , 那么我們需要寫(xiě)很多很多個(gè) not_show , 使用 getters 就可以解決這種問(wèn)題 :

export default {
    state:{//state
        show:false
    },
    getters:{
        not_show(state){//這里的state對(duì)應(yīng)著上面這個(gè)state
            return !state.show;
        }
    },
    mutations:{
        switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)state
            state.show = state.show?false:true;
            //你還可以在這里執(zhí)行其他的操作改變state
        }
    },
    actions:{
        switch_dialog(context){//這里的context和我們使用的$store擁有相同的對(duì)象和方法
            context.commit('switch_dialog');
            //你還可以在這里觸發(fā)其他的mutations方法
        },
    }
}

我們?cè)诮M件中使用 $store.state.dialog.show來(lái)獲得狀態(tài) show , 類(lèi)似的 , 我們可以使用 $store.getters.not_show來(lái)獲得狀態(tài) not_show 。

注意 : $store.getters.not_show的值是不能直接修改的 , 需要對(duì)應(yīng)的 state 發(fā)生變化才能修改商叹。

mapState、mapGetters只泼、mapActions
很多時(shí)候 , $store.state.dialog.show剖笙、$store.dispatch('switch_dialog')這種寫(xiě)法又長(zhǎng)又臭 , 很不方便 , 我們沒(méi)使用 vuex 的時(shí)候 , 獲取一個(gè)狀態(tài)只需要 this.show , 執(zhí)行一個(gè)方法只需要 this.switch_dialog 就行了 , 使用 vuex 使寫(xiě)法變復(fù)雜了 ?

使用 mapState、mapGetters请唱、mapActions 就不會(huì)這么復(fù)雜了弥咪。

以 mapState 為例 :

<template>
  <el-dialog :visible.sync="show"></el-dialog>
</template>

<script>
import {mapState} from 'vuex';
export default {
  computed:{

    //這里的三點(diǎn)叫做 : 擴(kuò)展運(yùn)算符
    ...mapState({
      show:state=>state.dialog.show
    }),
  }
}
</script>

相當(dāng)于 :

<template>
  <el-dialog :visible.sync="show"></el-dialog>
</template>

<script>
import {mapState} from 'vuex';
export default {
  computed:{
    show(){
        return this.$store.state.dialog.show;
    }
  }
}
</script>

mapGetters、mapActions 和 mapState 類(lèi)似 , mapGetters 一般也寫(xiě)在 computed 中 , mapActions 一般寫(xiě)在 methods 中十绑。

弄懂上面這些 , 你可以去看vuex文檔了 , 應(yīng)該能看懂了聚至。

項(xiàng)目地址:
vue2.x:https://github.com/momoSph/Vue2.x-ElementUI
vue3.x:https://github.com/momoSph/Vue3.x-ElementUI

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市本橙,隨后出現(xiàn)的幾起案子扳躬,更是在濱河造成了極大的恐慌,老刑警劉巖甚亭,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贷币,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡亏狰,警方通過(guò)查閱死者的電腦和手機(jī)役纹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)暇唾,“玉大人促脉,你說(shuō)我怎么就攤上這事辰斋。” “怎么了瘸味?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵宫仗,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我硫戈,道長(zhǎng)锰什,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任丁逝,我火速辦了婚禮汁胆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘霜幼。我一直安慰自己嫩码,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布罪既。 她就那樣靜靜地躺著铸题,像睡著了一般。 火紅的嫁衣襯著肌膚如雪琢感。 梳的紋絲不亂的頭發(fā)上丢间,一...
    開(kāi)封第一講書(shū)人閱讀 51,562評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音驹针,去河邊找鬼烘挫。 笑死,一個(gè)胖子當(dāng)著我的面吹牛柬甥,可吹牛的內(nèi)容都是我干的饮六。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼苛蒲,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼卤橄!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起臂外,我...
    開(kāi)封第一講書(shū)人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤窟扑,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后漏健,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體辜膝,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年漾肮,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了厂抖。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡克懊,死狀恐怖忱辅,靈堂內(nèi)的尸體忽然破棺而出七蜘,到底是詐尸還是另有隱情,我是刑警寧澤墙懂,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布橡卤,位于F島的核電站,受9級(jí)特大地震影響损搬,放射性物質(zhì)發(fā)生泄漏碧库。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一巧勤、第九天 我趴在偏房一處隱蔽的房頂上張望嵌灰。 院中可真熱鬧,春花似錦颅悉、人聲如沸沽瞭。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)驹溃。三九已至,卻和暖如春延曙,著一層夾襖步出監(jiān)牢的瞬間豌鹤,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工枝缔, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留布疙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓魂仍,卻偏偏與公主長(zhǎng)得像拐辽,于是被迫代替她去往敵國(guó)和親拣挪。 傳聞我的和親對(duì)象是個(gè)殘疾皇子擦酌,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容