Vuex(一) —— 集中式的狀態(tài)管理倉庫

目錄

  • Vue組件間通信方式回顧
    • 組件內(nèi)的狀態(tài)管理流程
    • 組件間通信方式
      • 父組件給子組件傳值 (最簡單的一種方式)
      • 子組件給父組件傳值
      • 不相關組件之間傳值
      • 其他常見方式($ref)
  • 簡易的狀態(tài)管理方案
    • 上面組件間通信方式的問題
    • 集中式的狀態(tài)管理方案
  • Vuex
    • 什么是Vuex?
    • 什么情況下使用Vuex?
      • 非必要的情況不要使用Vuex
      • 中大型單頁應用程序使用更好
    • Vuex核心概念回顧
    • Vuex基本結(jié)構(gòu)
    • State的使用
    • Getter的使用
    • Mutation的使用
      • Mutation的調(diào)試
        • 時光旅行
        • 狀態(tài)回滾
        • 提交改變
    • Actions的使用
    • Modules的使用
      • 模塊定義
      • 模塊注冊
      • 模塊使用
      • 添加命名空間
    • Vuex嚴格模式
    • Vuex插件
      • 插件的使用

年底最后一天來本來沒有想更博客,但是留下我今年還在努力學習的印記哈哈??戳税胩爝@居然是我第一個關于vue的博客,努力不算晚。先來對這個博客的內(nèi)容進行一下梳理,有興趣的小伙伴可以跳到自己感興趣的地方,這個博客比較長,長文警告。

image

Vue組件間通信方式回顧

組件內(nèi)的狀態(tài)管理流程

Vue最核心的兩個功能:數(shù)據(jù)驅(qū)動組件化

使用基于組件化的開發(fā),可以提高開發(fā)效率,帶來更好的可維護性。

new Vue({
    // state 組件內(nèi)部都可以管理自己的內(nèi)部狀態(tài)
    data () {
        return {
            count: 0
        }
    },
    // view 視圖,每個組件都有自己的視圖,把狀態(tài)綁定到視圖上,當用戶和視圖交互的時候,可能會更改狀態(tài)
    template: `<div>{{ count }}</div>`,
    // actions 行為,這里描述的是單個組件內(nèi)部的狀態(tài)管理,實際開發(fā)中可能多個組件可以共享狀態(tài)
    methods: {
        increment () {
            this.count++
        }
    }
})

這里說的狀態(tài)管理 —— 是通過狀態(tài),集中管理和分發(fā),解決多個組件共享狀態(tài)的問題。

  • state:狀態(tài),數(shù)據(jù)源。
  • view:視圖。通過把狀態(tài)綁定到視圖呈現(xiàn)給用戶
  • actions:用戶和視圖交互改變狀態(tài)的方式
image

圖中表明,狀態(tài)綁定到視圖上呈現(xiàn)給用戶,用戶通過與視圖交互改變狀態(tài),之后改變了的狀態(tài)再綁定到視圖會后呈現(xiàn)給用戶。
單向的數(shù)據(jù)流程很簡單清晰,但是多個組件共享數(shù)據(jù)會破壞這種簡單的結(jié)構(gòu)。

組件間通信方式的回顧

大多數(shù)情況下,組件都不是孤立存在的,他們需要共同協(xié)作構(gòu)成一個復雜的業(yè)務功能,在Vue中,為不同的組件關系提供了不同的通信規(guī)則。

常見的組件間通信的方式有:

父組件給子組件傳值 (最簡單的一種方式)

  • 父組件中給子組件通過相應屬性傳值
  • 子組件通過props接受數(shù)據(jù)
<!--子組件-->
<template>
  <div>
    <h1>Props Down Child</h1>
    <h2>{{ title }}</h2>
  </div>
</template>

<script>
export default {
  // 子組件中通過props來接收父組件傳的值
  // props可以是數(shù)組也可以是對象
  // 如果想約定傳值的類型用對象,這里title定了是string類型,如果傳number類型會報錯
  // props: ['title'],
  props: {
    title: String
  }
}
</script>

<style>

</style>
<!--父組件-->
<template>
  <div>
    <h1>Props Down Parent</h1>
    <!--2. 使用子組件的使用通過屬性給子組件傳值,這里也可以是表達式,綁定data中的成員-->
    <child title="My journey with Vue"></child>
  </div>
</template>

<script>
import child from './01-Child'
export default {
 // 1. 注冊子組件
  components: {
    child
  }
}
</script>

<style>

</style>

子組件給父組件傳值

  • 子組件通過自定義事件,用$emit觸發(fā)的時候攜帶參數(shù)給父組件傳值
  • 父組件通過$on注冊子組件內(nèi)部觸發(fā)的事件,并接收傳遞的數(shù)據(jù),行內(nèi)可以通過$event獲取事件傳遞的參數(shù) (事件處理函數(shù)中是不這么使用的)
<!--子組件-->
<template>
  <div>
    <h1 :style="{ fontSize: fontSize + 'em' }">Props Down Child</h1>
    <button @click="handler">文字增大</button>
  </div>
</template>

<script>
export default {
 // 通過props接收父組件傳的默認字體大小
  props: {
    fontSize: Number
  },
  methods: {
    handler () {
    // 當點擊按鈕的時候,觸發(fā)自定義事件enlargeText放大字體,讓字體放大0.1
    // this是當前子組件對象,this.$emit這個是由子組件觸發(fā)的自定義事件,當注冊事件的時候要給子組件注冊該事件
      this.$emit('enlargeText', 0.1)
    }
  }
}
</script>

<style></style>
<!--父組件-->
<template>
  <div>
  <!--父組件將fontSize進行綁定-->
    <h1 :style="{ fontSize: hFontSize + 'em'}">Event Up Parent</h1>

    這里的文字不需要變化
    <!--使用子組件,通過v-on給子組件設置了自定義方法enlargeText-->
    <child :fontSize="hFontSize" v-on:enlargeText="enlargeText"></child>
    <child :fontSize="hFontSize" v-on:enlargeText="enlargeText"></child>
    <!--還有一種在行內(nèi)獲取值的方式,獲取自定義事件傳遞數(shù)據(jù)的時候,直接通過$event獲取,這個值是觸發(fā)事件傳遞的0.1-->
    <child :fontSize="hFontSize" v-on:enlargeText="hFontSize += $event"></child>
  </div>
</template>

<script>
import child from './02-Child'
export default {
  components: {
    child
  },
  data () {
    return {
      hFontSize: 1
    }
  },
  methods: {
  // 子組件把值傳遞給了父組件,父組件通過參數(shù)接收到了值,進行運算
    enlargeText (size) {
      this.hFontSize += size
    }
  }
}
</script>

<style></style>

不相關組件之間傳值

  • 也是使用自定義事件的方式,但是因為沒有父子關系,所以不能通過子組件觸發(fā)傳值,所以這里需要使用eventBus,即創(chuàng)建一個公共的Vue實例,這個實例的作用是作為事件總線,或者事件中心。
  • eventBus:創(chuàng)建一個Vue實例,這個實例并不是用來展示內(nèi)容,所以沒有傳遞任何的選項,我們使用他的目的是使用$emit$on,用來觸發(fā)和注冊事件。
  • 觸發(fā)事件組件:通過$emit觸發(fā)事件,并傳遞參數(shù)
  • 注冊事件組件:通過$on注冊事件,接收參數(shù)進行處理
// eventbus.js
import Vue from 'vue'
export default new Vue()
<!--組件一:觸發(fā)事件-->
<template>
  <div>
    <h1>Event Bus Sibling01</h1>
    <div class="number" @click="sub">-</div>
    <input type="text" style="width: 30px; text-align: center" :value="value">
    <div class="number" @click="add">+</div>
  </div>
</template>

<script>
// 這個組件要觸發(fā)事件,將事件中心導入
import bus from './eventbus'

export default {
// props參數(shù)num
  props: {
    num: Number
  },
  // 因為props的值不能隨便改動,所以傳遞給value
  created () {
    this.value = this.num
  },
  data () {
    return {
      value: -1
    }
  },
  methods: {
  // 減值操作,判斷不能為0
    sub () {
      if (this.value > 1) {
        this.value--
        // 觸發(fā)bus的自定義事件numchange,并把value當參數(shù)傳遞出去
        bus.$emit('numchange', this.value)
      }
    },
    // 加值操作,和減值類似
    add () {
      this.value++
      bus.$emit('numchange', this.value)
    }
  }
}
</script>

<style>
.number {
  display: inline-block;
  cursor: pointer;
  width: 20px;
  text-align: center;
}
</style>
<!--組件二:定義-->
<template>
  <div>
    <h1>Event Bus Sibling02</h1>

    <div>{{ msg }}</div>
  </div>
</template>

<script>
// 因為要注冊事件,所以將事件中心導入
import bus from './eventbus'
export default {
  data () {
    return {
      msg: ''
    }
  },
  created () {
    // 通過bus注冊了numchange事件,事件處理函數(shù)中接收事件觸發(fā)時候傳遞的參數(shù),進行展示
    bus.$on('numchange', (value) => {
      this.msg = `您選擇了${value}件商品`
    })
  }
}
</script>

<style>

</style>
<!--App.vue-->
<template>
  <div id="app">
    <h1>不相關組件傳值</h1>
    <sibling0301 :num="num"></sibling0301>
    <sibling0302></sibling0302>
  </div>
</template>

<script>
import sibling0301 from './components/03-event-bus/03-Sibling-01'
import sibling0302 from './components/03-event-bus/03-Sibling-02'

export default {
  name: 'App',
  components: {
    sibling0301,
    sibling0302,
  },
  data () {
    return {
      num: 1
    }
  }
}
</script>

<style></style>

其他常見方式

  • $root,$parent$children,$ref,通過這幾種屬性獲取根組件成員,實現(xiàn)組件之間的通信。但這些都是不被推薦的方式。只有當項目很小,或者在開發(fā)自定義組件的時候,才會使用到。如果是大型項目的話,還是推薦使用Vuex管理狀態(tài)。

下面舉例通過$refs獲取子組件的狀態(tài),其他屬性可以自己查看文檔。

ref的兩個作用

  1. 在普通HTML標簽上使用ref,用$refs獲取到的是DOM對象
  2. 在組件標簽上使用ref,用$refs獲取到的是組件實例
<!--子組件,一個簡單的自定義組件,功能是能夠獲取焦點的自定義文本框。-->
<template>
  <div>
    <h1>ref Child</h1>
    <!--這個input標簽上設置了ref屬性-->
    <input ref="input" type="text" v-model="value">
  </div>
</template>

<script>
export default {
  data () {
    return {
      value: ''
    }
  },
  methods: {
    focus () {
      // 通過this.$refs.input獲取input的DOM對象,并調(diào)用其focus方法讓文本框獲取焦點
      this.$refs.input.focus()
    }
  }
}
</script>

<style></style>
<!--父組件,-->
<template>
  <div>
    <h1>ref Parent</h1>
    <!--在子組件的標簽上設置了ref-->
    <child ref="c"></child>
  </div>
</template>

<script>
import child from './04-Child'
export default {
  components: {
    child
  },
  mounted () {
    // 這里想要拿到子組件的話,必須要等組件渲染完畢,所以這里在mounted函數(shù)下
    // 這里通過this.$refs.c就是子組件對象,拿到這個對象就可以訪問其屬性和方法
    // 這里調(diào)用子組件方法讓其內(nèi)部獲取焦點
    this.$refs.c.focus()
    // 通過value屬性給文本框賦值
    this.$refs.c.value = 'hello input'
  }
}
</script>

<style>

</style>

還是一句話不建議使用,如果濫用這種方式的話可以造成狀態(tài)管理的混亂。

簡易的狀態(tài)管理方案

上面組件間通信方式的問題

如果多個組件之間需要共享狀態(tài),使用之前演示的方式雖然都可以實現(xiàn),但是比較麻煩,而且多個組件之間進行傳值,很難跟蹤到數(shù)據(jù)的變化。如果出現(xiàn)問題的話,很難定位問題。當遇到多個組件需要共享狀態(tài)的時候,典型的場景如購物車,我們使用之前介紹的方案都不合適,可能會遇到以下的問題:

  • 多個視圖依賴同一狀態(tài),如果多層嵌套的組件依賴同一狀態(tài),使用父子組件傳值可以實現(xiàn),但是非常麻煩而且不易管理。
  • 來自不同視圖的行為需要變更同一狀態(tài),我們可以通過父子組件的方式對狀態(tài)進行修改,或者通過事件機制來改變,或者同步狀態(tài)的變化,以上這些方式非常的脆弱,通常會導致產(chǎn)生無法維護的代碼。

集中式的狀態(tài)管理方案

為了解決這些問題,我們把不同組件的共享狀態(tài)抽取出來,存儲到一個全局對象中并且將來使用的時候保證其實響應式的。這個對象創(chuàng)建好之后里面有全局的狀態(tài)和修改狀態(tài)的方法,我們的任何組件都可以獲取和通過調(diào)用對象中的方法修改全局對象中的狀態(tài) (組件中不允許直接修改對象的state狀態(tài)屬性)。

把多個組件的狀態(tài)放到一個集中的地方存儲,并且可以檢測到數(shù)據(jù)的更改,這里先不使用Vuex,我們自己先進行一個簡單的實現(xiàn)。

  1. 創(chuàng)建一個全局的store.js

集中式的狀態(tài)管理,所有的狀態(tài)都在這里。這個模塊中導出了一個對象,這對象就是狀態(tài)倉庫且全局唯一的對象,任何組件都可以導入這個模塊使用

這里面有state,還有actions,state是用來存儲狀態(tài),actions是用戶交互更改視圖用的。還有一個debug的屬性,方便開發(fā)調(diào)試。

// store.js
export default {
  debug: true,
  state: {
    user: {
      name: 'xiaomao',
      age: 18,
      sex: '男'
    }
  },
  setUserNameAction (name) {
    if (this.debug) {
      console.log('setUserNameAction triggered:', name)
    }
    this.state.user.name = name
  }
}
  1. 在組件中導入
<!--組件A-->
<template>
  <div>
    <h1>componentA</h1>
    <!--3. 可以在視圖中直接用點的方式顯示數(shù)據(jù)-->
    user name: {{ sharedState.user.name }}
    <button @click="change">Change Info</button>
  </div>
</template>

<script>
// 1. 在組件中導入store
import store from './store'
export default {
  methods: {
    // 4. 當點擊按鈕的時候,調(diào)用store的方法,將值改為componentA
    change () {
      store.setUserNameAction('componentA')
    }
  },
  data () {
    return {
      // 當前組件還可以有自己的私有狀態(tài),存在privateState中
      privateState: {},
      // 2. 將store的state屬性賦值給shareState
      sharedState: store.state
    }
  }
}
</script>

<style></style>
<!--組件B,用法與上面一樣,就是修改名字的時候值為componentB-->
<template>
  <div>
    <h1>componentB</h1>
    user name: {{ sharedState.user.name }}
    <button @click="change">Change Info</button>
  </div>
</template>

<script>
import store from './store'
export default {
  methods: {
    change () {
      // 修改名字的時候改成了componentB
      store.setUserNameAction('componentB')
    }
  },
  data () {
    return {
      privateState: {},
      sharedState: store.state
    }
  }
}
</script>

<style></style>

上面組件A和組件B都共享了全局的狀態(tài),并且用戶都可以更改狀態(tài)。調(diào)試的時候,按A組件的按鈕兩者都變成了componentA,點B組件的按鈕兩者都變成了componentB

我們不在組件中直接修改狀態(tài)的值而是通過調(diào)用storeactions來修改值,這樣記錄的好處是: 能夠記錄store中所以state的變更,當可以實現(xiàn)記錄storestate的變更時候,就可以實現(xiàn)高級的調(diào)試功能。例如:timeTravel(時光旅行)和歷史回滾功能。

剛才使用的store,其實就類似于Vuex的倉庫。

當項目比較復雜,多個組件共享狀態(tài)的時候,使用組件間通信的方式比較麻煩,而且需要維護。這個時候我們可以使用集中式的狀態(tài)解決方案 —— Vuex

Vuex

好的終于進入了主題~~

什么是Vuex?

  • Vuex官網(wǎng)
  • Vuex 是專門為 Vue.js 設計的狀態(tài)管理庫,從使用的角度其實就是一個JavaScript
  • 它采用集中式的方式存儲需要共享的數(shù)據(jù),如果狀態(tài)特別多的話不易管理,所以Vuex還提供了一種模塊的機制,按照模塊管理不同的狀態(tài)
  • 它的作用是進行狀態(tài)管理,解決復雜組件通信,數(shù)據(jù)共享
  • Vuex 也集成到 Vue 的官方調(diào)試工具 devtools extension,提供了time-travel時光旅行、歷史回滾、狀態(tài)快照、導入導出等高級調(diào)試功能

什么情況下使用Vuex?

非必要的情況不要使用Vuex

Vuex 可以幫助我們管理組件間共享的狀態(tài),但是在項目中使用Vuex的話,我們需要了解Vuex中帶來的新的概念和一些API,如果項目不大,并且組件間共享狀態(tài)不多的情況下,這個時候使用Vuex給我們帶來的益處并沒有付出的時間多。此時使用簡單的 store 模式 或者其他方式就能滿足我們的需求。

中大型單頁應用程序使用更好

中大型單頁應用程序中,使用Vuex可以幫我們解決多個視圖依賴同一狀態(tài)、來自不同視圖的行為需要變更同一狀態(tài)的問題。建議符合這些情況的業(yè)務,使用Vuex進行狀態(tài)管理,會給我們提供更好的處理組件的狀態(tài),帶來的收益會更好些。例如典型案例:購物車。

注意:不要濫用Vuex,否則會讓業(yè)務變得更復雜。

Vuex核心概念回顧

下面這張圖展示了Vuex的核心概念并且展示了Vuex的整個工作流程

image
  • Store:倉庫,Store是使用Vuex應用程序的核心,每個應用僅有一個Store,它是一個容器,包含著應用中的大部分狀態(tài),當然我們不能直接改變Store中的狀態(tài),我們要通過提交Mutations的方式改變狀態(tài)。
  • State:狀態(tài),保存在Store中,因為Store是唯一的,所以State也是唯一的,稱為單一狀態(tài)樹,這里的狀態(tài)是響應式的。
  • Getter:相當于Vuex中的計算屬性,方便從一個屬性派生出其他的值,它內(nèi)部可以對計算的結(jié)果進行緩存,只有當依賴的狀態(tài)發(fā)生改變的時候,才會重新計算。
  • Mutation:狀態(tài)的變化必須要通過提交Mutation來完成。
  • Actions:與Mutation類似,不同的是可以進行異步的操作,內(nèi)部改變狀態(tài)的時候都需要改變Mutation。
  • Module:模塊,由于使用的單一狀態(tài)樹讓所有的狀態(tài)都會集中到一個比較大的對象中,應用變得很復雜的時候,Store對象就會變得相當臃腫,為了解決這些問題Vuex允許我們將Store分割成模塊,每個模塊擁有自己的StateMutationActions,Getter,甚至是嵌套的子模塊。

Vuex基本結(jié)構(gòu)

使用vue-cli創(chuàng)建項目的時候,如果選擇了Vuex,會自動生成Vuex的基本結(jié)構(gòu)。

// store.js
import Vue from 'vue'
// 導入Vuex插件
import Vuex from 'vuex'
// 通過use方法注冊插件
// 插件內(nèi)部把Vuex的Store注入到了Vue的實例上
Vue.use(Vuex)
// 創(chuàng)建了Vuex的Store對象并且導出
export default new Vuex.Store({
    state: {
        ...
    },
    mutations: {
        ...
    },
    actions: {
        ...
    },
    modules: {
        ...
    }
    // 如果有需要還可以有getters
})
//App.js
// 導入store對象
import store from './store'
new Vue({
    router,
    // 在初始化Vue的時候傳入store選項,這個選項會被注入到Vue實例中
    // 我們在組件中使用的this.$store就是在這個地方注入的
    store,
    render: h => h(App)
}).$mount('#app')

State的使用

  1. 下載項目模板vuex-sample-temp ,npm install下載依賴,在store/index.js中定義兩個state
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0,
    msg: 'hello vue'
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})
  1. App.vue中使用state,然后使用npm run serve查看結(jié)果
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    count: {{ $store.state.count}} <br/>
    msg: {{ $store.state.ms }}
  </div>
</template>
<script>
  1. 每次使用變量都要前面寫 $store.state 很是麻煩,所以這里使用``Vuex內(nèi)部提供的myState的函數(shù),會幫我們生成狀態(tài)對應的計算屬性
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    <!--4. 在使用的時候直接用計算屬性count和msg即可-->
    count: {{ count }} <br/>
    msg: {{ msg }}
  </div>
</template>
<script>
  // 1. 引入vuex的mapState模塊
  import { mapState } from 'vuex'
  export default {
    // 2. 在計算屬性中調(diào)用mapState函數(shù)
    computed: {
      // 3. mapState需要接收數(shù)組作為參數(shù),數(shù)組的元素是需要映射的狀態(tài)屬性
      // 會返回一個對象,包含兩個對應屬性計算的方法
      // { count: state => state.count, msg: state => state.msg }
      // 然后這里使用擴展運算符展開對象,完成之后我們就有了count和msg兩個計算屬性
      ...mapState(['count', 'msg'])
    }
  }
</script>
  1. 上面的方法比較簡潔但是如果這個組件中本身就有count或者msg屬性,就會造成名稱沖突,這個時候需要設置別名。
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    <!-- 使用的時候直接使用別名即可 -->
    count: {{ num }} <br/>
    msg: {{ message }}
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  computed: {
    // mapState可以傳對象,鍵是別名,值是映射的狀態(tài)屬性
    ...mapState({ num: 'count', message: 'msg' })
  }
}
</script>

Getter的使用

Vuex中的getter就相當于組件中的計算屬性,如果想要對state的數(shù)據(jù)進行簡單的處理在展示,可以使用getter

這里用Vuexgetter處理而不是用組件中的計算屬性是因為狀態(tài)本身屬于Vuex,應該在其內(nèi)部處理

  1. store.js中設置getters
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0,
    msg: 'hello vue'
  },
  // 與計算屬性的寫法一致
  getters: {
    reverseMsg (state) {
      return state.msg.split('').reverse().join('')
    }
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

  1. App.vue中使用
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    <h2>reverseMsg: {{ $store.getters.reverseMsg }}</h2>
    <br/>
  </div>
</template>
  1. 同樣那樣引用過于麻煩,那么和mapState一樣,使用內(nèi)部的mapGetters,也是將其映射到組件的計算屬性,其用法和mapState一樣,也可以為了避免沖突使用對象設置別名。
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    <h2>reverseMsg: {{ reverseMsg }}</h2>
    <br/>
  </div>
</template>
<script>
// 1. 引入vuex的mapGetters模塊
import { mapGetters } from 'vuex'
export default {
  // 2. 在計算屬性中調(diào)用mapGetters函數(shù)
  computed: {
    // 3. 用法與mapState一致,這里也可以使用對象設置別名
    ...mapGetters(['reverseMsg'])
  }
}
</script>

Mutation的使用

狀態(tài)的修改必須提交Mutation,Mutation必須是同步執(zhí)行的。

  1. 當用戶點擊按鈕的時候,count值進行增加,先在store.js中寫Mutation函數(shù)
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0,
    msg: 'hello vue'
  },
  mutations: {
    // 增加函數(shù),接收兩個參數(shù)
    // 第一個state狀態(tài)
    // 第二個是payload載荷,payload是mutations的時候提交的額外參數(shù),可以是對象,這里傳遞的是數(shù)字
    increate (state, payload) {
      state.count += payload
    }
  },
  actions: {
  },
  modules: {
  }
})

  1. App.vue中設置按鈕,并注冊事件
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    count: {{ $store.state.count }} <br/>
    <h2>Mutation</h2>
    <!-- 給按鈕注冊點擊事件,點擊的時候調(diào)用commit提交Mutation,第一個參數(shù)是調(diào)用的方法名,第二個參數(shù)是payload,傳遞的數(shù)據(jù) -->
    <button @click="$store.commit('increate', 2)">Mutation</button>
  </div>
</template>
  1. 點擊按鈕的時候,count的值每次+2
  2. 下面進行寫法優(yōu)化,使用map方法將當前的mutation映射到methods中,其依舊會返回一個對象,這個對象中存儲的是mutation中映射的方法
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    count: {{ $store.state.count }} <br/>
    <h2>Mutation</h2>
    <!-- 這里直接寫方法,,第一個參數(shù)state不需要傳遞,后面?zhèn)鱬ayload參數(shù)為3 -->
    <button @click="increate(3)">Mutation</button>
  </div>
</template>
<script>
// 1. 引入vuex的mapMutations模塊
import { mapMutations } from 'vuex'
export default {
  // 2. methods中調(diào)用mapMutations方法
  methods: {
    ...mapMutations(['increate'])
  }
}
</script>

Mutation的調(diào)試

運行到4之后,這時看一下devtools看一下時光旅行和歷史回滾,下面是初始狀態(tài)

image

點一下按鈕之后就增加了一個記錄,還顯示了改變之后的數(shù)據(jù)

image

如果數(shù)據(jù)不對,可以進行調(diào)試。

時光旅行

然后多點幾下,進行時光旅行。

image

點擊按鈕之后,狀態(tài)就變成了之前那個狀態(tài),這個功能也是為了方便調(diào)試

image
狀態(tài)回滾

這個圖標就是狀態(tài)回滾

image

點擊之后,代碼就回到了沒有執(zhí)行這一步的狀態(tài)

image
提交改變

下面那個按鈕的意思是將這次提交作為最后一次提交

image

點擊之后,base State變成了那次的狀態(tài),其他的狀態(tài)以這個作為起始點

image

Actions的使用

如果有異步的修改,需要使用actions,在actions中可以執(zhí)行異步操作,當異步操作結(jié)束后,如果需要更改狀態(tài),還需要提交Mutation。

  1. actions中添加方法increateAsync
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0,
    msg: 'hello vue'
  },
  mutations: {
    increate (state, payload) {
      state.count += payload
    }
  },
  actions: {
    // actions中的方法有兩個參數(shù):第一個參數(shù)是context上下文,這個對象中有state,commit,getters等成員,第二個參數(shù)是payLoad
    increateAsync (context, payLoad) {
      setTimeout(() => {
        context.commit('increate', payLoad)
      }, 2000)
    }
  },
  modules: {
  }
})
  1. App.vue中使用dispatch,actions的方法都要用這個
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    count: {{ $store.state.count }} <br/>
    <h2>Actions</h2>
    <!--這里使用了dispatch-->
    <button @click="$store.dispatch('increateAsync',5)">Action</button>
  </div>
</template>
  1. 進行優(yōu)化,這個時候引入mapActions
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    count: {{ $store.state.count }} <br/>
    <h2>Actions</h2>
    <button @click="increateAsync(5)">Action</button>
  </div>
</template>
<script>
// 1. 引入vuex的mapActions模塊
import { mapActions } from 'vuex'
export default {
  methods: {
    // 這個是對Actions的方法的映射,把this.increateAsync映射到this.$store.dispatch
    ...mapActions(['increateAsync'])
  }
}
</script>

Modules的使用

模塊可以讓我們把單一狀態(tài)樹拆分成多個模塊,每個模塊都可以擁有自己的state,mutation,action,getter甚至嵌套子模塊。

模塊定義

store文件夾中,創(chuàng)建一個modules文件夾,里面每一個js文件就是一個模塊,下面是每一個模塊的定義格式

const state = {
  products: [
    { id: 1, title: 'iPhone 11', price: 8000 },
    { id: 2, title: 'iPhone 12', price: 10000 }
  ]
}
const getters = {}
const mutations = {
  setProducts (state, payload) {
    state.products = payload
  }
}
const actions = {}

export default {
  namespaced: false,
  state,
  getters,
  mutations,
  actions
}

模塊注冊

  1. 先導入這個模塊
import products from './modules/products'
import cart from './modules/cart'
  1. 后來在modules選項中注冊,注冊之后這里會把模塊掛載到storestate中,這里可以通過store.state.products訪問到products模塊中的成員,還把的模塊中的mutation成員記錄到了store的內(nèi)部屬性_mutation中,可以通過commit直接提交mutation。
export default new Vuex.Store({
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {
    products,
    cart
  }
})

模塊使用

  1. App.vue中使用,state就點出來,mutation還是用commit方法
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    <h2>Modules</h2>
    <!--第一個products是products模塊,第二個products是模塊的state的products屬性-->
    products: {{ $store.state.products.products }} <br/>
    <button @click="store.commit('setProducts',[])">Mutation</button>
  </div>
</template>

添加命名空間

因為每個模塊中的mutation是可以重名的,所以推薦使用命名空間的用法,方便管理。

  1. 在開啟命名空間的時候,在模塊的導出部分添加namespaced
const state = {}
const getters = {}
const mutations = {}
const actions = {}

export default {
  // true就是開啟,false或者不寫就是關閉
  namespaced: false,
  state,
  getters,
  mutations,
  actions
}

  1. 使用的時候在App.vue中要設置state是模塊中出來的,如果沒有命名空間,就是全局的state的。
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    products: {{ products }} <br/>
    <button @click="setProducts([])">Mutation</button>
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
  computed: {
    // 模塊中的state,第一個參數(shù)寫模塊名稱,第二個參數(shù)寫數(shù)組或者對象
    ...mapState('products', ['products'])
  },
  methods: {
    // 模塊中的mutations,第一個寫模塊名稱,第二個寫數(shù)組或者對象
    ...mapMutations('products', ['setProducts'])
  }
}
</script>

Vuex嚴格模式

所有的狀態(tài)變更必須提交mutation,但是如果在組件中獲取到$store.state.msg進行修改,語法層面沒有問題,卻破壞了Vuex的約定,且devTools也無法跟蹤到狀態(tài)的修改,開啟嚴格模式之后,如果在組件中直接修改state,會報錯。

  1. index.js,初始化Store的時候開啟嚴格模式
export default new Vuex.Store({
  strict: true,
  state: {
    ...
  },
  ...
}
  1. App.vue中使用直接賦值的語句
<template>
  <div id="app">
    <h1>Vuex - Demo</h1>
    <h2>strict</h2>
    <button @click="$store.state.msg = 'hello world~'">strict</button>
  </div>
</template>
  1. 點擊按鈕內(nèi)容改變,但是控制臺會拋出錯誤
image

注意:不要在生產(chǎn)環(huán)境開啟嚴格模式,因為嚴格模式會深度檢測狀態(tài)樹,會影響性能。在開發(fā)模式中開啟嚴格模式,在生產(chǎn)環(huán)境中關閉嚴格模式

export default new Vuex.Store({
 strict: process.env.NODE_ENV !== 'production',
 state: {
  ...
}

Vuex插件

  • Vuex插件就是一個函數(shù),接收一個store的參數(shù)
  • 在這個函數(shù)中可以注冊函數(shù)讓其在所有的mutations結(jié)束之后再執(zhí)行

插件的使用

  • 插件應該在創(chuàng)建Store之前去創(chuàng)建
  • subscribe函數(shù)
    • 作用是去訂閱store中的mutation
    • 他的回調(diào)函數(shù)會在每個mutation之后調(diào)用
    • subscribe會接收兩個參數(shù),第一個是mutation,還可以區(qū)分模塊的命名空間,第二個參數(shù)是state,里面是存儲的狀態(tài)
  1. 定義插件
// 這個函數(shù)接收store參數(shù)
const myPlugin = store => {
    // 當store初始化后調(diào)用
    store.subscribe((mutation, state) => {
        // 每次 mutation 之后調(diào)用
        // mutation 的格式為 { type, payload }
        // type里面的格式是 "模塊名/state屬性"
        // state 的格式為 { 模塊一, 模塊二 }
    })
}
  1. Store中注冊插件
const store = new Vuex.Store({
    //...
    plugins: [myPlugin]
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

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