官網: Vuex 是什么? | Vuex (vuejs.org)
目錄
介紹
1、安裝
2、新建?store/index.js?專門存放 vuex?
3、 在 main.js 中導入掛載到 Vue 實例上?
?核心概念
1、核心概念 -state 狀態
1、訪問Vuex中的數據?
2、通過$store訪問的語法
3、通過輔助函數
2、 核心概念-mutations
1.定義mutations
2.格式說明
3.組件中提交 mutations
?4、輔助函數- mapMutations
?3、核心概念 - actions
1.定義actions
2.組件中通過dispatch調用
?3、輔助函數 -mapActions
4、 核心概念 - getters
1.定義getters
2.使用getters
2.1原始方式-$store
2.2輔助函數 - mapGetters
5、 核心概念 - module
1、模塊定義?- 準備 state
2、獲取模塊內的state數據
3、獲取模塊內的getters數據?
4、獲取模塊內的mutations方法?
?
5、獲取模塊內的actions方法
?Vuex模塊化的使用小結
1.直接使用
2.借助輔助方法使用
介紹
Vuex 是一個專為 Vue.js 應用程序開發的狀態管理模式。它采用集中式存儲管理應用的所有組件的狀態,并以相應的規則保證狀態以一種可預測的方式發生變化。Vuex 也集成到 Vue 的官方調試工具?devtools extension?(opens new window),提供了諸如零配置的 time-travel 調試、狀態快照導入導出等高級調試功能。
1、安裝
npm i vuex@3
2、新建?store/index.js
?專門存放 vuex?
// 導入 vue
import Vue from 'vue'
// 導入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 進行插件的安裝初始化
Vue.use(Vuex)// 創建倉庫 store
const store = new Vuex.Store()// 導出倉庫
export default store
3、 在 main.js 中導入掛載到 Vue 實例上?
import Vue from 'vue'
import App from './App.vue'
//導入
import store from './store'Vue.config.productionTip = falsenew Vue({render: h => h(App),
//掛載store
}).$mount('#app')
?
?核心概念
1、核心概念 -state 狀態
tate提供唯一的公共數據源,所有共享的數據都要統一放到Store中的State中存儲。
打開項目中的store.js文件,在state對象中可以添加我們要共享的數據。
// 創建倉庫 store
const store = new Vuex.Store({// state 狀態, 即數據, 類似于vue組件中的data,// 區別:// 1.data 是組件自己的數據, // 2.state 中的數據整個vue項目的組件都能訪問到state: {count: 101}
})
1、訪問Vuex中的數據?
- 通過$store直接訪問 —> {{ $store.state.count }}
- 通過輔助函數mapState 映射計算屬性 —> {{ count }}
?
2、通過$store訪問的語法
獲取 store:1.Vue模板中獲取 this.$store2.js文件中獲取 import 導入 store模板中: {{ $store.state.xxx }}
組件邏輯中: this.$store.state.xxx
JS模塊中: store.state.xxx
3、通過輔助函數
- mapState獲取 state中的數據?
1.第一步:導入mapState (mapState是vuex中的一個函數)
import { mapState } from 'vuex'
2.第二步:采用數組形式引入state屬性
mapState(['count'])
上面代碼的最終得到的是?類似于
count () {return this.$store.state.count
}
3.第三步:利用展開運算符將導出的狀態映射給計算屬性
computed: {...mapState(['count'])}
?
?
?
2、 核心概念-mutations
1.定義mutations
const store = new Vuex.Store({
strict: true,state: {count: 0},// 定義mutationsmutations: {}
})
開啟嚴格模式
通過?strict: true
?可以開啟嚴格模式,開啟嚴格模式后,直接修改state中的值會報錯
state數據的修改只能通過mutations,并且mutations必須是同步的
?
2.格式說明
mutations是一個對象,對象中存放修改state的方法
mutations: {// 方法里參數 第一個參數是當前store的state屬性// payload 載荷 運輸參數 調用mutaiions的時候 可以傳遞參數 傳遞載荷addCount (state) {state.count += 1}},2.1 提供mutation函數(帶參數)
mutations: {...addCount (state, count) {state.count = count}
},
3.組件中提交 mutations
this.$store.commit('addCount')2.2 提交mutation
handle ( ) {this.$store.commit('addCount', 10)
}
小tips: 提交的參數只能是一個, 如果有多個參數要傳, 可以傳遞一個對象this.$store.commit('addCount', {count: 10
})
?Vuex中的值和組件中的input雙向綁定案例
App.vue
<input :value="count" @input="handleInput" type="text">export default {methods: {handleInput (e) {// 1. 實時獲取輸入框的值const num = +e.target.value// 2. 提交mutation,調用mutation函數this.$store.commit('changeCount', num)}}
}
store/index.js
mutations: { changeCount (state, newCount) {state.count = newCount}
},
?4、輔助函數- mapMutations
mapMutations和mapState很像,它把位于mutations中的方法提取了出來,我們可以將它導入
import { mapMutations } from 'vuex'
methods: {...mapMutations(['addCount'])
}
上面代碼的含義是將mutations的方法導入了methods中,等價于
methods: {// commit(方法名, 載荷參數)addCount () {this.$store.commit('addCount')}}
此時,就可以直接通過this.addCount調用了
<button @click="addCount">值+1</button>
?
?
?3、核心概念 - actions
state是存放數據的,mutations是同步更新數據 (便于監測數據的變化, 更新視圖等, 方便于調試工具查看變化),
actions則負責進行異步操作
說明:mutations必須是同步的
1.定義actions
new Vuex.Store({mutations: {changeCount (state, newCount) {state.count = newCount}
}
actions: {setAsyncCount (context, num) {// 一秒后, 給一個數, 去修改 numsetTimeout(() => {context.commit('changeCount', num)}, 1000)}
},
}
?
2.組件中通過dispatch調用
setAsyncCount () {this.$store.dispatch('setAsyncCount', 1111)
}
?3、輔助函數 -mapActions
import { mapActions } from 'vuex'
methods: {...mapActions(['setAsyncCount']) setAsyncCount//為Actions中的方法名
}//mapActions映射的代碼 本質上是以下代碼的寫法
//methods: {
// changeCountAction (n) {
// this.$store.dispatch('setAsyncCount', n)
// },
//}
直接通過 this.方法 就可以調用
核心概念 -
4、 核心概念 - getters
從state中篩選出符合條件的一些數據,這些數據是依賴state的,此時會用到getters
1.定義getters
getters: {// getters函數的第一個參數是 state// 必須要有返回值filterList: state => state.list.filter(item => item > 5)}
2.使用getters
2.1原始方式-$store
<div>{{ $store.getters.filterList }}</div>
2.2輔助函數 - mapGetters
computed: {...mapGetters(['filterList'])
}
<div>{{ filterList }}</div>
?
?
5、 核心概念 - module
如果把所有的狀態都放在state中,當項目變得越來越大的時候,Vuex會變得越來越難以維護
由此,又有了Vuex的模塊化
1、模塊定義?- 準備 state
定義模塊?user?
user中管理用戶的信息狀態 userInfo?modules/user.js
const state = {userInfo: {name: 'zs',age: 18}
}const mutations = {}const actions = {}const getters = {}export default {state,mutations,actions,getters
}
?
在store/index.js
文件中的modules配置項中,注冊這個模塊
import user from './modules/user'
import setting from './modules/setting'const store = new Vuex.Store({modules:{user}
})
使用模塊中的數據, 可以直接通過模塊名訪問?
$store.state.模塊名.xxx
?=>?$store.state.user.userInfo
也可以通過 mapState 映射
2、獲取模塊內的state數據
- 直接通過模塊名訪問 $store.state.模塊名.xxx? ?
$store.state.user.userInfo.name
- 通過 mapState 映射:
- 默認根級別的映射 mapState([ 'xxx' ])
...mapState('user', ['userInfo']),
- 子模塊的映射 :mapState('模塊名', ['xxx']) - 需要開啟命名空間?namespaced:true
?
3、獲取模塊內的getters數據?
- 直接通過模塊名訪問
$store.getters['模塊名/xxx ']
<div>{{ $store.getters['user/UpperCaseName'] }}</div>
- 通過 mapGetters 映射
- 默認根級別的映射?
mapGetters([ 'xxx' ])
- 子模塊的映射?
mapGetters('模塊名', ['xxx'])
?- 需要開啟命名空間computed:{...mapGetters('user', ['UpperCaseName']) }
- 默認根級別的映射?
?
4、獲取模塊內的mutations方法?
默認模塊中的 mutation 和 actions 會被掛載到全局,需要開啟命名空間,才會掛載到子模塊。
namespaced:true
調用方式:
- 直接通過 store 調用 $store.commit('模塊名/xxx ', 額外參數)
- 通過 mapMutations 映射
- 默認根級別的映射 mapMutations([ 'xxx' ])
- 子模塊的映射 mapMutations('模塊名', ['xxx']) - 需要開啟命名空間
...mapMutations('user', ['setUser']),
?
modules/user.js
const mutations = {setUser (state, newUserInfo) {state.userInfo = newUserInfo}
}
5、獲取模塊內的actions方法
調用語法:
- 直接通過 store 調用 $store.dispatch('模塊名/xxx ', 額外參數)
- 通過 mapActions 映射
- 默認根級別的映射 mapActions([ 'xxx' ])
- 子模塊的映射 mapActions('模塊名', ['xxx']) - 需要開啟命名空間
modules/user.js
const mutations = {setUser (state, newUserInfo) {state.userInfo = newUserInfo}
}const actions = {setUserSecond (context, newUserInfo) {// 將異步在action中進行封裝setTimeout(() => {// 調用mutation context上下文,默認提交的就是自己模塊的action和mutationcontext.commit('setUser', newUserInfo)}, 1000)}
}
mapActions映射
<button @click="setUserSecond({ name: 'xc', age: 20 })">一秒后更新信息</button>methods:{...mapActions('user', ['setUserSecond'])
}
?
?Vuex模塊化的使用小結
1.直接使用
- state --> $store.state.模塊名.數據項名
- getters --> $store.getters['模塊名/屬性名']
- mutations --> $store.commit('模塊名/方法名', 其他參數)
- actions --> $store.dispatch('模塊名/方法名', 其他參數)
2.借助輔助方法使用
1.import { mapXxxx, mapXxx } from 'vuex'
computed、methods: {
? //?...mapState、...mapGetters放computed中;
? //?...mapMutations、...mapActions放methods中;
? ...mapXxxx('模塊名', ['數據項|方法']),
? ...mapXxxx('模塊名', { 新的名字: 原來的名字 }),
}
2.組件中直接使用 屬性?{{ age }}
?或 方法?@click="updateAge(2)"