vue --- [全家桶] Vuex
生活随笔
收集整理的這篇文章主要介紹了
vue --- [全家桶] Vuex
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. Vuex 概述
1.1 組件之間共享數(shù)據(jù)的方式
- 父向子傳值: v-bind 屬性綁定
- 子向父?jìng)髦? v-on 事件綁定
- 兄弟組件之間共享數(shù)據(jù): EventBus
- $on: 接收數(shù)據(jù)的那個(gè)組件
- $emit: 發(fā)送數(shù)據(jù)的那個(gè)組件
1.2 Vuex是什么
Vuex: 是實(shí)現(xiàn)組件全局狀態(tài)(數(shù)據(jù))管理的一種機(jī)制,可以方便的實(shí)現(xiàn)組件之間數(shù)據(jù)的共享
1.3 使用Vuex統(tǒng)一管理狀態(tài)的好處
[vuex中存儲(chǔ)的數(shù)據(jù)] : 一般情況下,只有組件之間共享的數(shù)據(jù),才有必存儲(chǔ)到vuex中;對(duì)于組件中私有數(shù)據(jù),依舊存儲(chǔ)在組件自身的data即可
2. Vuex的基本使用
- 安裝vuex依賴包
- 導(dǎo)入vuex包
- 創(chuàng)建store對(duì)象
- 將store對(duì)象掛在到vue實(shí)例中
3. Vuex的核心概念
3.1 State
State提供唯一的公共數(shù)據(jù)源,所有共享的數(shù)據(jù)都要統(tǒng)一放到Store的State中進(jìn)行存儲(chǔ)
// 創(chuàng)建store數(shù)據(jù)源,提供唯一公共數(shù)據(jù) const store = new Vuex.Store({state: { count: 0 } })組件訪問State中數(shù)據(jù)的第一種方式:
this.$store.state.全局?jǐn)?shù)據(jù)名稱組件訪問State中數(shù)據(jù)的第二種方式
// 1. 從 vuex中按需導(dǎo)入mapState函數(shù) import { mapState } from 'vuex'// 2. 將全局?jǐn)?shù)據(jù),映射為當(dāng)前組件的計(jì)算屬性 computed: {...mapState(['count']) }3.2 Mutation
- Mutation用于變更Store中的數(shù)據(jù),不推薦以下做法改變?nèi)謹(jǐn)?shù)據(jù)(this.$store.state.count)
3.2.1 $store.commit
// 定義Mutation const store = new Vuex.Store({state: {count: 0},mutations: {add(state) {// 變更狀態(tài)state.count++}} })// 觸發(fā)mutation methods:{handle1() {this.$store.commit('add')} }可以在觸發(fā)mutations時(shí)傳遞參數(shù):
// 定義mutation const store = new Vuex.Store({state: {count: 0},mutations: {addN(state, step){// 變更狀態(tài)state.count += step}} })// 觸發(fā)mutation methods:{handle2(){this.$store.commit('addN', 3)} }3.2.2 mapMutations
// 1. 從vuex中按需導(dǎo)入mapMutations函數(shù) import { mapMutations } from 'vuex'// 2. 將指定的mutations函數(shù),映射為當(dāng)前組件的methods函數(shù) methods:{...mapMutations(['add','addN']) }3.3 Action
3.3.1 $store.dispatch
- Action用于處理異步任務(wù)
- 如果通過異步操作變更數(shù)據(jù),必須通過Action,而不能使用Mutation,但是在Action中還是要通過觸發(fā)Mutation的方式間接變更數(shù)據(jù)
- 攜帶參數(shù)的actions異步任務(wù)
3.3.2 mapActions
// 1. 從 vuex中按需導(dǎo)入 mapActions函數(shù) import { mapActions } from 'vuex'// 2. 在methods中使用 methods:{...mapActions['addAsync','addNAsync'] }3.4 Getter
3.4.1 $store.getters
- 用于對(duì)Store中的數(shù)據(jù)進(jìn)行處理形成新的數(shù)據(jù)
- 可以對(duì)Store中已有的數(shù)據(jù)加工處理之后形成新的數(shù)據(jù),類似Vue的計(jì)算屬性
- Store中數(shù)據(jù)發(fā)生變化,Getter的數(shù)據(jù)也會(huì)跟著變化
3.4.2 mapGetters
import { mapGetters } from 'vuex'computed: {...mapGetters(['showNum']) }總結(jié)
以上是生活随笔為你收集整理的vue --- [全家桶] Vuex的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 符号_液压图形符号识别之减压阀符号原理
- 下一篇: vue element 实现树形菜单栏n