什么是Vuex ?
Vuex是專門為Vue.js應用開發的狀態管理模式,采用集中式存盤所有組件的狀態,讓組件之間可以通信
用人話說就是: vuex就是專門用來管理vue的資料的,統一在一個檔案中存盤公共的資料
Vuex中有個5個內容需要學習:
- state — 存盤公共的資料
- mutations — 修改資料
- getters — 類似與computed(計算屬性),用于計算資料后得到新的資料
- actions — 用于發起異步的請求(獲取資料)
- modules — 模塊化拆分
- 重點: 需要掌握state和mutations 的使用
使用步驟:
- 下載vuex (npm i vuex)
- 在src目錄下創建一個檔案夾統一取名為 store ,在store中創建index.js
- 新建的index.js中有如下代碼:
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
export default new vuex.Store({
state: {},
mutations: {},
getters: {},
actions: {},
modules: {}
})
注意: 別忘了向Vue實體中注入store
import store from './store'
new Vue({
store,
render: h => h(App),
}).$mount('#app')
1. state
state類似于組件中的data(){return{}} 用來存放資料
示例:
export default new vuex.Store({
// 手動定義一些資料
state:{
a: 10
}
})
接下來我們在組件中獲取并使用一下這個公共的資料
<template>
<div>
{{$store.state.a}} // 頁面中列印出10
</div>
</template>
2. mutations
mutations主要用于修改state中的資料
引數一: state對應 state物件
引數二: 形參- 需要傳入的引數,可有可無
語法: mutations:{‘mutations名’:funtion(state,形參) }
例子: 在state中a = 10 , 我們定義一個mutations方法 對state中的a的值進行修改
代碼如下:
export default new vuex.Store({
state: {
a: 10
},
mutations: {
state.a += 1 // a+1
},
})
接下來在App.vue中我們寫一個button按鈕用來點擊并呼叫這個方法 點一次觸發一次 讓a的值每次加一
<template>
<div>
{{$store.state.a}}
// 點擊一次 就呼叫一次 進行+1
<button @click="$store.commit('add')">a+1</button>
</div>
</template>
注:
- 在模板中: $store.commit(‘mutations名’)
- 在組件中: 要加this呼叫, this.$store.commit(‘mutations名’)
3. getters
語法: getters:{ ‘getters名’,function(state,形參)},用法和mutations差不多,
getters的作用是用于計算資料得到計算后的新的資料 類似于computed計算資料
示例: 例如在state中有一個值為b:[1,2,3,4,5],
用getters對這個資料進行計算 然后列印到頁面中,具體代碼如下:
getters: {
sum: function (state) {
return state.b.reduce((temp, item) => temp + item, 0)
}
}
在頁面中渲染出來{{$store.getters.sum}} // 15
4. actions
語法: actions:{ ‘action名’,function(context,形參)}
context其實就是對應的state .
actions用于發起異步的請求,可以在actions中用axios發起資料請求,獲取資料
繼續看示例代碼:
//
state:{
book:[ ]
},
mutations:{
updateBook:function(state,newbook){
state.book = newbook
}
}
actions: {
getBooks: function (context) {
axios({
url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books',
method: 'get'
}).then(res => {
console.log(res);
context.commit('updateBook', res.data.data)
})
}
}
注意: 在state中我定義了一個陣列 book:[ ]用來接識訓取到的資料 , 接收到資料res后, 想賦值給book陣列, 但是要記住不能直接進行賦值,必須要在mutations中定義一個賦值的函式, 在actions獲取到資料.呼叫mutations中的函式,進行賦值.
接著組件中寫一個button按鈕用來測驗 觸發actions發起axios請求獲取資料,并賦值給book陣列
呼叫actions的方式:
模塊中: $store.dispatch(‘actions名’)
組件中: this.store.dispatch(‘actions名’)
<template>
<div>
// 點擊 觸發actions 并發起axios請求資料
<button @click="$store.dispatch('getBooks')">獲取資料</button>
{{$store.state.book}} // 列印獲取到的資料
</div>
</template>
modules
modules默認namespaced: 為false ,設定true后.,在組件中使用拆分到modules的資料和方法要加"模塊名"
語法: modules:{ ‘模塊名’:{state{},mutations:{},getters:{},actions:{} }}
modules用來拆分index.js中的代碼, 減少index.js中代碼的繁多和體積,讓index.js中更簡潔,把相同的需要的資料和方法都提取到同一個js中
示例: 這里我就隨便的寫幾個進行拆分提取
前提: 在store檔案中新建modules檔案,把state中book陣列和mutations中修改book的方法
以及actions中獲取資料的相關代碼剪切到,modules檔案中的新建的allBook.js檔案中
import axios from 'axios'
export default {
state: {
b: [1, 2, 3, 4, 5],
book: []
},
mutations: {
updateBook: function (state, newbook) {
state.book = newbook
}
},
getters: {
sum: function (state) {
return state.b.reduce((temp, item) => temp + item, 0)
}
},
actions: {
getBooks: function (context) {
axios({
url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books',
method: 'get'
}).then(res => {
console.log(res);
context.commit('updateBook', res.data.data)
})
}
}
}
抽離到allBook.js中后,在index.js中引入,并添加到modules物件中
import Vue from 'vue'
import vuex from 'vuex'
import allBook from './modules/allBook.js'
Vue.use(vuex)
export default new vuex.Store({
modules: {
allBook
}
})
注意: 抽離后.組件中呼叫的方式就變了, 還記得我們加了namespaced: true這句話, 加了之后,參考資料和方法時都必須要加上模塊名了
示例: 如何呼叫
以及其他三個呼叫方式:
// 例子:
1. // 原先寫法: {{$store.getters.sum}} // 15
2. // 抽離后的寫法: {{$store.gerters['allBook/sum']}} // 15
// 這里我都列舉一下其他三種的方式
// state:
$store.state.模塊名.屬性名
// mutations:
$store.commit('模塊名/mutation名')
// getters:
$store.gerters['模塊名/getter名']
// actions:
$store.dispatch('模塊名/action名')
補充: 如果要修改state/mutations/getters/actions名字,例如:可以這樣寫 $store.commit(‘模塊名,{新名字,久名字}’) ,其他的格式都類似如此
Vuex的輔助函式map系列用法匯總
mapState/mapMutations/mapGetters/mapActions
用來優化訪問的方式, 普通的寫法太麻煩了,利用vuex內置的方法,可以簡潔的參考vuex中的資料和方法
1. mapState函式
將state中的變數映射到當前組件中使用
使用步驟,代碼如下:
// 當前組件中 按需引入mapState
// 例如參考vuex中state中的變數 c:30
<template>
{{c}} // 30
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['c'])
// 如果需要改名字的話
...mapState({'新名字':'舊名字'})
}
}
</script>
computed:{ …mapState() } 這里的…是物件的展開運算子,整體來看是物件的合并,
2. mapMutations
不多bb ,上代碼自行體會:
// 在state中定義一個變數為a:10
// App.vue組件中
<template>
<div>
{{a}}
<button @click="abb">點擊+1</button>
</div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
export default {
computed: {
...mapState(['a'])
},
methods: {
...mapMutations(['add'])
},
}
</script>
// index.js中
export default new vuex.Store({
state: {
a: 10,
},
mutations: {
add: function (state) {
state.a += 1
}
},
})
以上列舉了mapState和mapMutations的語法,其他兩個(mapGetters和mapActions)用法和前兩個都是一樣的,自行體會吧,脖子酸了,休息會,不寫了
接下來講一下在全域中和modules情況下使用map系列的用法:
如何使用全域state
-
直接使用: this.$store.state.xxx;
-
map輔助函式:
computed: { ...mapState(['xxx']), ...mapState({'新名字': 'xxx'}) }
如何使用modules中的state
-
直接使用: this.$store.state.模塊名.xxx;
-
map輔助函式:
computed: { ...mapState('模塊名', ['xxx']), ...mapState('模塊名', {'新名字': 'xxx'}) }
如何使用全域getters
-
直接使用:
this.$store.getters.xxx -
map輔助函式:
computed: { ...mapGetters(['xxx']), ...mapGetters({'新名字': 'xxx'}) }
如何使用modules中的getters
-
直接使用:
this.$store.getters.模塊名.xxx -
map輔助函式:
computed: { ...mapGetters('模塊名', ['xxx']), ...mapGetters('模塊名',{'新名字': 'xxx'}) }
如何使用全域mutations
-
直接使用:
this.$store.commit('mutation名', 引數) -
map輔助函式:
methods: { ...mapMutations(['mutation名']), ...mapMutations({'新名字': 'mutation名'}) }
如何使用modules中的mutations(namespaced:true)
-
直接使用:
this.$store.commit('模塊名/mutation名', 引數) -
map輔助函式:
methods: { ...mapMutations('模塊名', ['xxx']), ...mapMutations('模塊名',{'新名字': 'xxx'}) }
如何使用全域actions
-
直接使用:
this.$store.dispatch('action名', 引數) -
map輔助函式:
methods: { ...mapActions(['actions名']), ...mapActions({'新名字': 'actions名'}) }
如何使用modules中的actions(namespaced:true)
-
直接使用:
this.$store.dispatch('模塊名/action名', 引數) -
map輔助函式:
methods: { ...mapActions('模塊名', ['xxx']), ...mapActions('模塊名',{'新名字': 'xxx'}) }
Vuex中五大核心和actions/mutations/state思路圖
- 五大核心API

- Actions

- State和Mutations以及Mutations

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/304348.html
標籤:其他
